timer.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. # The implementation is adopted from mmcv,
  2. # made publicly available under the Apache 2.0 License at
  3. # https://github.com/open-mmlab/mmcv/blob/master/mmcv/utils/timer.py
  4. from time import time
  5. class TimerError(Exception):
  6. def __init__(self, message):
  7. self.message = message
  8. super(TimerError, self).__init__(message)
  9. class Timer:
  10. """A flexible Timer class.
  11. Example:
  12. >>> import time
  13. >>> import mmcv
  14. >>> with mmcv.Timer():
  15. >>> # simulate a code block that will run for 1s
  16. >>> time.sleep(1)
  17. 1.000
  18. >>> with mmcv.Timer(print_tmpl='it takes {:.1f} seconds'):
  19. >>> # simulate a code block that will run for 1s
  20. >>> time.sleep(1)
  21. it takes 1.0 seconds
  22. >>> timer = mmcv.Timer()
  23. >>> time.sleep(0.5)
  24. >>> print(timer.since_start())
  25. 0.500
  26. >>> time.sleep(0.5)
  27. >>> print(timer.since_last_check())
  28. 0.500
  29. >>> print(timer.since_start())
  30. 1.000
  31. """
  32. def __init__(self, start=True, print_tmpl=None):
  33. self._is_running = False
  34. self.print_tmpl = print_tmpl if print_tmpl else '{:.3f}'
  35. if start:
  36. self.start()
  37. @property
  38. def is_running(self):
  39. """bool: indicate whether the timer is running"""
  40. return self._is_running
  41. def __enter__(self):
  42. self.start()
  43. return self
  44. def __exit__(self, type, value, traceback):
  45. print(self.print_tmpl.format(self.since_last_check()))
  46. self._is_running = False
  47. def start(self):
  48. """Start the timer."""
  49. if not self._is_running:
  50. self._t_start = time()
  51. self._is_running = True
  52. self._t_last = time()
  53. def since_start(self):
  54. """Total time since the timer is started.
  55. Returns (float): Time in seconds.
  56. """
  57. if not self._is_running:
  58. raise TimerError('timer is not running')
  59. self._t_last = time()
  60. return self._t_last - self._t_start
  61. def since_last_check(self):
  62. """Time since the last checking.
  63. Either :func:`since_start` or :func:`since_last_check` is a checking
  64. operation.
  65. Returns (float): Time in seconds.
  66. """
  67. if not self._is_running:
  68. raise TimerError('timer is not running')
  69. dur = time() - self._t_last
  70. self._t_last = time()
  71. return dur
  72. _g_timers = {} # global timers
  73. def check_time(timer_id):
  74. """Add check points in a single line.
  75. This method is suitable for running a task on a list of items. A timer will
  76. be registered when the method is called for the first time.
  77. Example:
  78. >>> import time
  79. >>> import mmcv
  80. >>> for i in range(1, 6):
  81. >>> # simulate a code block
  82. >>> time.sleep(i)
  83. >>> mmcv.check_time('task1')
  84. 2.000
  85. 3.000
  86. 4.000
  87. 5.000
  88. Args:
  89. timer_id (str): Timer identifier.
  90. """
  91. if timer_id not in _g_timers:
  92. _g_timers[timer_id] = Timer()
  93. return 0
  94. else:
  95. return _g_timers[timer_id].since_last_check()