A timer as a context manager. Wraps around a timer. A custom timer can be passed to the constructor. The default timer is timeit.default_timer. Note that the latter measures wall clock time, not CPU time! On Unix systems, it corresponds to time.time. On Windows systems, it corr
| 3 | |
| 4 | |
| 5 | class Timer: # deprecated, use tqdm instead |
| 6 | """A timer as a context manager. |
| 7 | |
| 8 | Wraps around a timer. A custom timer can be passed |
| 9 | to the constructor. The default timer is timeit.default_timer. |
| 10 | |
| 11 | Note that the latter measures wall clock time, not CPU time! |
| 12 | On Unix systems, it corresponds to time.time. |
| 13 | On Windows systems, it corresponds to time.clock. |
| 14 | |
| 15 | Parameters |
| 16 | ---------- |
| 17 | print_at_exit : boolean |
| 18 | If True, print when exiting context. |
| 19 | format : str |
| 20 | `ms`, `s` or `datetime`. |
| 21 | |
| 22 | References |
| 23 | ---------- |
| 24 | - https://github.com/brouberol/contexttimer/blob/master/contexttimer/__init__.py. |
| 25 | |
| 26 | |
| 27 | """ |
| 28 | |
| 29 | def __init__(self, fmt='s', print_at_exit=True, timer=timeit.default_timer): |
| 30 | assert fmt in ['ms', 's', 'datetime'], "`fmt` should be 'ms', 's' or 'datetime'!" |
| 31 | self._fmt = fmt |
| 32 | self._print_at_exit = print_at_exit |
| 33 | self._timer = timer |
| 34 | self.start() |
| 35 | |
| 36 | def __enter__(self): |
| 37 | """Start the timer in the context manager scope.""" |
| 38 | self.restart() |
| 39 | return self |
| 40 | |
| 41 | def __exit__(self, exc_type, exc_value, exc_traceback): |
| 42 | """Print the end time.""" |
| 43 | if self._print_at_exit: |
| 44 | print(str(self)) |
| 45 | |
| 46 | def __str__(self): |
| 47 | return self.fmt(self.elapsed)[1] |
| 48 | |
| 49 | def start(self): |
| 50 | self.start_time = self._timer() |
| 51 | |
| 52 | restart = start |
| 53 | |
| 54 | @property |
| 55 | def elapsed(self): |
| 56 | """Return the current elapsed time since last (re)start.""" |
| 57 | return self._timer() - self.start_time |
| 58 | |
| 59 | def fmt(self, second): |
| 60 | if self._fmt == 'ms': |
| 61 | time_fmt = second * 1000 |
| 62 | time_str = '%s %s' % (time_fmt, self._fmt) |