Context Manager for Timing Blocks
Wrap a code block in a context manager that measures elapsed time, so timing instrumentation is added without clutter or manual bookkeeping.
Code
import time
from contextlib import contextmanager
@contextmanager
def timer(label: str):
start = time.perf_counter()
try:
yield
finally:
elapsed_ms = (time.perf_counter() - start) * 1000
print(f"{label}: {elapsed_ms:.2f}ms")
with timer("query"):
total = sum(i * i for i in range(10000))Report a problem with this exampleOpens a pre-filled issue on GitHub.