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