3 # © Copyright 2021-2022, Scott Gasch
5 """A simple stopwatch decorator / context for timing things."""
9 from typing import Callable, Literal
12 class Timer(contextlib.AbstractContextManager):
14 A stopwatch to time how long something takes (walltime).
18 with stopwatch.Timer() as t:
22 print(f'That took {walltime} seconds.')
25 def __init__(self) -> None:
29 def __enter__(self) -> Callable[[], float]:
30 """Returns a functor that, when called, returns the walltime of the
33 self.start = time.perf_counter()
35 return lambda: self.end - self.start
37 def __exit__(self, *args) -> Literal[False]:
38 self.end = time.perf_counter()