Various
[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
20     def __enter__(self) -> Callable[[], float]:
21         self.start = time.perf_counter()
22         self.end = 0.0
23         return lambda: self.end - self.start
24
25     def __exit__(self, *args) -> bool:
26         self.end = time.perf_counter()
27         return True