A flexible Timer class. Example: >>> import time >>> import mmcv >>> with mmcv.Timer(): >>> # simulate a code block that will run for 1s >>> time.sleep(1) 1.000 >>> with mmcv.Timer(print_tmpl='it takes {:.1f} seconds'): >>> # simulate a code block tha
| 12 | |
| 13 | |
| 14 | class Timer: |
| 15 | """A flexible Timer class. |
| 16 | Example: |
| 17 | |
| 18 | >>> import time |
| 19 | >>> import mmcv |
| 20 | >>> with mmcv.Timer(): |
| 21 | >>> # simulate a code block that will run for 1s |
| 22 | >>> time.sleep(1) |
| 23 | 1.000 |
| 24 | >>> with mmcv.Timer(print_tmpl='it takes {:.1f} seconds'): |
| 25 | >>> # simulate a code block that will run for 1s |
| 26 | >>> time.sleep(1) |
| 27 | it takes 1.0 seconds |
| 28 | >>> timer = mmcv.Timer() |
| 29 | >>> time.sleep(0.5) |
| 30 | >>> print(timer.since_start()) |
| 31 | 0.500 |
| 32 | >>> time.sleep(0.5) |
| 33 | >>> print(timer.since_last_check()) |
| 34 | 0.500 |
| 35 | >>> print(timer.since_start()) |
| 36 | 1.000 |
| 37 | """ |
| 38 | |
| 39 | def __init__(self, start=True, print_tmpl=None): |
| 40 | self._is_running = False |
| 41 | self.print_tmpl = print_tmpl if print_tmpl else '{:.3f}' |
| 42 | if start: |
| 43 | self.start() |
| 44 | |
| 45 | @property |
| 46 | def is_running(self): |
| 47 | """bool: indicate whether the timer is running""" |
| 48 | return self._is_running |
| 49 | |
| 50 | def __enter__(self): |
| 51 | self.start() |
| 52 | return self |
| 53 | |
| 54 | def __exit__(self, type, value, traceback): |
| 55 | print(self.print_tmpl.format(self.since_last_check())) |
| 56 | self._is_running = False |
| 57 | |
| 58 | def start(self): |
| 59 | """Start the timer.""" |
| 60 | if not self._is_running: |
| 61 | self._t_start = time() |
| 62 | self._is_running = True |
| 63 | self._t_last = time() |
| 64 | |
| 65 | def since_start(self): |
| 66 | """Total time since the timer is started. |
| 67 | Returns (float): Time in seconds. |
| 68 | """ |
| 69 | if not self._is_running: |
| 70 | raise TimerError('timer is not running') |
| 71 | self._t_last = time() |
no outgoing calls
no test coverage detected
searching dependent graphs…