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