utils_others.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import time
  2. import socket
  3. import logging
  4. from collections import OrderedDict
  5. def print_with_no(obj):
  6. if hasattr(obj, '__len__'):
  7. for k, item in enumerate(obj):
  8. print('[{}/{}] {}'.format(k+1, len(obj), item))
  9. elif hasattr(obj, '__iter__'):
  10. for k, item in enumerate(obj):
  11. print('[{}] {}'.format(k+1, item))
  12. else:
  13. print('[1] {}'.format(obj))
  14. def get_file_line_count(filename):
  15. line_count = 0
  16. buffer_size = 1024 * 1024 * 8
  17. with open(filename, 'r') as f:
  18. while True:
  19. data = f.read(buffer_size)
  20. if not data:
  21. break
  22. line_count += data.count('\n')
  23. return line_count
  24. def get_host_ip():
  25. try:
  26. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  27. s.connect(('8.8.8.8', 80))
  28. ip = s.getsockname()[0]
  29. finally:
  30. s.close()
  31. return ip
  32. class ContextTimer(object):
  33. """
  34. References:
  35. WithTimer in https://github.com/uber/ludwig/blob/master/ludwig/utils/time_utils.py
  36. """
  37. def __init__(self, name=None, use_log=True, quiet=False):
  38. self.use_log = use_log
  39. self.quiet = quiet
  40. if name is None:
  41. self.name = ''
  42. else:
  43. self.name = '{}, '.format(name.rstrip())
  44. def __enter__(self):
  45. self.start_time = time.time()
  46. if not self.quiet:
  47. self._print_or_log('{}{} starts'.format(self.name, self._now_time_str))
  48. return self
  49. def __exit__(self, exc_type, exc_val, exc_tb):
  50. if not self.quiet:
  51. self._print_or_log('{}elapsed_time = {:.5}s'.format(self.name, self.get_eplased_time()))
  52. self._print_or_log('{}{} ends'.format(self.name, self._now_time_str))
  53. @property
  54. def _now_time_str(self):
  55. return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
  56. def _print_or_log(self, output_str):
  57. if self.use_log:
  58. logging.info(output_str)
  59. else:
  60. print(output_str)
  61. def get_eplased_time(self):
  62. return time.time() - self.start_time
  63. def enter(self):
  64. """Manually trigger enter"""
  65. self.__enter__()