Skip to content

Lesson 2 of 9 · 21m

Benchmarks That Survive Review

Microbenchmarks lie in predictable ways: warmup, allocator noise, timing granularity, and dead-code elimination. Build measurements you would trust in an incident review.

A bad benchmark is worse than no benchmark because it creates false certainty. Python makes this easy: the interpreter is warm one moment and cold the next, list allocations reuse memory, and the operating system moves your process between cores while you are congratulating yourself on a 7% win.

The objective is not a perfect number. It is a repeatable comparison that answers a narrow question.

Use timeit for small, isolated decisions

python -m timeit -s 'rows=[(i, str(i)) for i in range(1000)]' 'dict(rows)'

In code, measure multiple repetitions and compare the best steady-state result:

import timeit

setup = "rows = [(i, str(i)) for i in range(1000)]"
results = timeit.repeat("dict(rows)", setup=setup, number=1000, repeat=7)
print("best seconds per loop:", min(results) / 1000)
print("all repeats:", [round(r / 1000, 8) for r in results])

timeit disables garbage collection during the run. That reduces noise but can hide GC pressure; for allocation-heavy code, note the caveat or benchmark with GC explicitly enabled.

Know what the number means

The minimum is usually the least-noisy estimate of what the code can cost. The mean is useful when you care about user-visible consistency. Report both if tails matter. Never report a single run unless the operation takes minutes and the measurement is obviously stable.

A useful benchmark output looks like evidence, not applause:

baseline: min 42.1 ms, mean 44.8 ms, n=7
patched:  min 31.4 ms, mean 33.0 ms, n=7
ratio:    0.75x time / 1.34x speedup

"About twice as fast" is not a measurement.

Macrobenchmarks are the real gate

Microbenchmarks answer implementation questions: dict(rows) versus a comprehension, regex A versus regex B. They do not answer product questions. For those, measure the whole operation end to end:

start = time.perf_counter()
result = rebuild_search_index(corpus)
elapsed = time.perf_counter() - start

Use perf_counter for elapsed time, not time.time; it is monotonic and designed for intervals. Include realistic input sizes, cold-cache behavior if relevant, and the downstream effects of your optimization. A faster parser that allocates three times as much can still lose under memory pressure.

Control the easy variables

Close the browser tabs you care about? No — control the machine honestly: same Python build, same CPU governor situation, same input, same process count, no debugger attached. If results swing wildly, increase repetitions before trusting clever statistics.

Field notes

  • Compare relative change on the same machine; absolute numbers rarely transfer to production hardware.
  • Keep benchmark inputs immutable and versioned. A changing fixture makes history useless.
  • If the optimized branch is inside noise, do not ship it for performance. Ship it only if it is simpler or more correct.
  • Put a benchmark in CI only after it is stable. A flaky performance test becomes an ignored performance test.

Was this lesson helpful?

Sign in to rate