Timing context manager in Python
Context managers guarantee cleanup; this one measures elapsed time.
import time
from contextlib import contextmanager
@contextmanager
def timed(label):
start = time.perf_counter()
try:
yield
finally:
elapsed = time.perf_counter() - start
print(f"{label}: {elapsed:.3f}s")
How it works
@contextmanagerturns the generator into a with-block helper.- Code before the
yieldruns on entry, recording the start time. - The
finallyblock always prints the elapsed time on exit.
Keywords and builtins used here
deffinallyprinttimedtryyield
The run, in numbers
- Lines
- 11
- Characters to type
- 204
- Tokens
- 50
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 29 seconds.
Step 2 of 5 in Protocols & context managers, step 16 of 53 in Pythonic Python.