Easier and more self documenting patterns for loading/saving Persistent
[python_utils.git] / stopwatch.py
1 #!/usr/bin/env python3
2
3 # © Copyright 2021-2022, Scott Gasch
4
5 """A simple stopwatch decorator / context for timing things."""
6
7 import contextlib
8 import time
9 from typing import Callable, Literal
10
11
12 class Timer(contextlib.AbstractContextManager):
13     """
14     A stopwatch to time how long something takes (walltime).
15
16     e.g.
17
18         with stopwatch.Timer() as t:
19             do_the_thing()
20
21         walltime = t()
22         print(f'That took {walltime} seconds.')
23     """
24
25     def __init__(self) -> None:
26         self.start = 0.0
27         self.end = 0.0
28
29     def __enter__(self) -> Callable[[], float]:
30         """Returns a functor that, when called, returns the walltime of the
31         operation in seconds.
32         """
33         self.start = time.perf_counter()
34         self.end = 0.0
35         return lambda: self.end - self.start
36
37     def __exit__(self, *args) -> Literal[False]:
38         self.end = time.perf_counter()
39         return False