More cleanup, yey!
[python_utils.git] / stopwatch.py
1 #!/usr/bin/env python3
2
3 """A simple stopwatch decorator / context for timing things."""
4
5 import time
6 from typing import Callable, Optional
7
8
9 class Timer(object):
10     """
11     A stopwatch to time how long something takes (walltime).
12
13     e.g.
14
15         with stopwatch.Timer() as t:
16             do_the_thing()
17
18         walltime = t()
19         print(f'That took {walltime} seconds.')
20     """
21
22     def __init__(self) -> None:
23         self.start = 0.0
24         self.end = 0.0
25
26     def __enter__(self) -> Callable[[], float]:
27         """Returns a functor that, when called, returns the walltime of the
28         operation in seconds.
29         """
30         self.start = time.perf_counter()
31         self.end = 0.0
32         return lambda: self.end - self.start
33
34     def __exit__(self, *args) -> Optional[bool]:
35         self.end = time.perf_counter()
36         return None  # don't suppress exceptions