Rename timer; add a test for OutputContext.
[python_utils.git] / stopwatch.py
1 #!/usr/bin/env python3
2
3 import time
4 from typing import Callable
5
6
7 class Timer(object):
8     """
9     with timer.Timer() as t:
10         do_the_thing()
11
12     walltime = t()
13     print(f'That took {walltime}s.')
14     """
15
16     def __init__(self) -> None:
17         self.start = None
18         self.end = None
19         pass
20
21     def __enter__(self) -> Callable[[], float]:
22         self.start = time.perf_counter()
23         self.end = 0.0
24         return lambda: self.end - self.start
25
26     def __exit__(self, *args) -> bool:
27         self.end = time.perf_counter()
28         return True