DEV Community

Alex Chen
Alex Chen

Posted on

Quick Tip: Time Any Python Block with a 3-Line Context Manager (No timeit Boilerplate)

Quick Tip

timeit is for micro-benchmarks. When you just want "how slow is this function in production?", I use this 3-liner:

from contextlib import contextmanager
from time import perf_counter

@contextmanager
def timer(label="block"):
    t0 = perf_counter()
    yield
    print(f"{label}: {perf_counter() - t0:.3f}s")
Enter fullscreen mode Exit fullscreen mode

Usage — no restructuring your code, no decorator hunting:

with timer("fetch"):
    data = fetch_all_records()

with timer("transform"):
    cleaned = [normalize(r) for r in data]
Enter fullscreen mode Exit fullscreen mode

Output:

fetch: 0.412s
transform: 1.847s
Enter fullscreen mode Exit fullscreen mode

Why not time.time()? perf_counter is monotonic — NTP adjustments can't make your timing negative. Why not a decorator? Context managers time arbitrary blocks, including half a function, without extracting anything.

I sprinkled five of these through a slow ETL script last week and found 80% of the time was in one regex. Two minutes of instrumentation, one-line fix.

What do you reach for first when something's slow — cProfile, py-spy, or printf-style timing like this?

Powered by MonkeyCode — the free, open-source AI coding assistant: https://ly.cyberserval.tech/iIETXiF

Top comments (0)