Sub topic 13
Keeping the speedup: benchmarks in your workflow
You have profiled a slow program, fixed the hot spot, and confirmed the gain. This chapter covers what keeps that gain from disappearing. I assume you can write pytest tests, you know timeit and time.perf_counter from earlier chapters, and you can read a profiler report.
Why speedups regress
A speedup is a property of the code at one moment. Later changes can undo it without any test failing:
- Someone replaces a set with a list because "order would be nice."
- A new feature adds a call inside a hot loop.
- A dependency upgrade changes how a function behaves.
- A refactor removes a cache decorator that looked redundant.
Ordinary unit tests only check that the output is correct, and a slow function still returns correct output. A performance guard is a test that fails when the code gets slower than you accept.
Performance tests have a weakness that correctness tests lack: their results depend on the machine. A laptop, a busy CI runner, and a production server will all report different times for the same code. Most of this chapter is about designing guards that survive that variation.
Four kinds of guard
| Guard | What it checks | Noise resistance | Typical use |
|---|---|---|---|
| Absolute threshold | "Finishes in under 50 ms" | Low, since it depends on hardware | Hard service limits on known hardware |
| Ratio against a baseline | "At least 20x faster than the naive version" | High, since both run on the same machine | Protecting an algorithmic fix |
| Operation count | "Makes exactly N calls or cache misses" | Perfect, since it is deterministic | Protecting caching and call-count fixes |
| Saved-run comparison | "No more than 15% slower than the last saved run" | Medium, and needs a stable machine | Tracking drift across commits |
Pick the most deterministic guard that still captures the property you care about. A count of cache misses never flakes. A wall-clock threshold flakes often.
A ratio guard with timeit
An algorithmic fix usually gives a large factor, such as 100x or 1000x. A guard that demands a modest fraction of that factor will pass on any hardware and still catch the regression that matters.
The script below keeps the slow version as a reference and tests the fast version against it. Run it directly, or let pytest collect test_fast_version_stays_faster.
import timeit
def has_duplicates_slow(items):
for i, a in enumerate(items):
for b in items[i + 1:]:
if a == b:
return True
return False
def has_duplicates_fast(items):
return len(set(items)) != len(items)
def best_time(func, *args, repeat=5, number=3):
"""Return the best per-call time in seconds over several repeats."""
runs = timeit.repeat(lambda: func(*args), repeat=repeat, number=number)
return min(runs) / number
def test_fast_version_stays_faster():
data = list(range(2_000)) # all unique, so the slow version does full work
assert has_duplicates_slow(data) == has_duplicates_fast(data)
slow = best_time(has_duplicates_slow, data)
fast = best_time(has_duplicates_fast, data)
# The real gap is in the hundreds. Requiring 20x leaves a wide safety margin.
assert fast * 20 < slow, f"fast={fast:.6f}s slow={slow:.6f}s"
if __name__ == "__main__":
test_fast_version_stays_faster()
print("ok")Three details matter here.
- The test first asserts that both functions return the same result. A function that got faster by returning the wrong answer must not pass.
- The input is all unique values. With duplicates near the front, the slow version exits early and the comparison tells you nothing.
- The helper takes the minimum over several repeats, not the mean. The next section explains why.
An operation-count guard
Some optimizations are best guarded by counting work. If you added lru_cache so a recursive function does linear work, assert the linear count directly. This test cannot flake, because it never reads a clock.
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
def test_fib_does_linear_work():
fib.cache_clear()
assert fib(60) == 1548008755920
info = fib.cache_info()
# One miss per distinct argument 0..60. A lost cache would mean billions.
assert info.misses == 61
if __name__ == "__main__":
test_fib_does_linear_work()
print("ok")Call cache_clear() at the start of the test. Otherwise an earlier test that called fib leaves entries behind and changes the miss count.
The same idea works for other fixes. You can count database queries, file reads, or calls to an expensive function by wrapping it with a counter or a unittest.mock spy.
Saved-run comparison with pytest-benchmark
Sometimes you have no slow reference to compare against, and you want to know whether this commit is slower than the last one. The pytest-benchmark plugin runs a function many times, reports statistics, and can save results to disk for later comparison.
Install it and write a benchmark. The benchmark fixture calls your function repeatedly and returns its result, so you can still assert on correctness.
pip install pytest pytest-benchmark# test_bench.py
def has_duplicates_fast(items):
return len(set(items)) != len(items)
def test_has_duplicates_fast(benchmark):
data = list(range(10_000))
result = benchmark(has_duplicates_fast, data)
assert result is FalseSave a baseline on a known-good commit, then compare later runs against it:
pytest test_bench.py --benchmark-autosave
pytest test_bench.py --benchmark-compare --benchmark-compare-fail=mean:15%The first command writes a JSON file under .benchmarks/. The second compares the new run with the most recent saved one and exits with a failure if the mean is more than 15% worse. You can also set the failure metric to min, which is steadier on noisy machines.
Saved comparisons are only meaningful when both runs happened on comparable hardware. A baseline saved on your laptop and compared on a CI runner will produce meaningless differences.
Handling noise
Timing noise is the main reason teams abandon performance tests. These habits reduce it:
- Warm up first. The first call may populate caches, import modules, or build lazy structures.
timeitandpytest-benchmarkalready repeat the call, but a hand-written timer needs a throwaway first call. - Time only the work you care about. Build inputs outside the timed region. Do not include printing or file writes.
- Use inputs large enough to matter. A function that takes a microsecond is dominated by timer overhead. Choose a size where the difference between good and bad code is large.
- Leave generous margins. If the improvement is 300x, a 20x guard still catches a real regression and ignores a noisy runner.
- Keep the slow reference small. The naive version runs inside your test suite, so use input sizes that finish in a second or two.
- Run benchmarks separately from unit tests. Slow, timing-sensitive tests belong in their own job, so a flaky timing never blocks a fix for a correctness bug.
Where benchmarks fit in the workflow
The cycle below connects everything in this tutorial. Measurement comes before the fix, and the guard comes after it.
When a guard fails, treat it as a prompt to investigate. Profile the code again before deciding whether to fix the regression or relax the threshold. Sometimes a slowdown is an acceptable price for a new feature, and then you update the guard on purpose, with a commit message that says why.
Common errors
- Guarding with a tight absolute limit. A test that demands "under 10 ms" passes on your machine and fails on a loaded runner. Prefer ratios and counts, or leave large margins.
- Comparing means on a shared machine. One noisy run drags the mean up. Compare minimums, or use the median.
- Benchmarking the wrong input. If the test data is small or lucky, such as duplicates found at the first element, the benchmark passes even after the algorithm regresses.
- Forgetting correctness. A guard that only measures time will accept a function that returns early with the wrong value. Assert on the result.
- Letting state leak between tests. Caches survive across tests in one process. Clear them, or the second test measures a warm cache and hides a regression.
- Guarding everything. Each guard costs run time and maintenance. Protect the few fixes that gave large gains on paths users notice, and skip the rest.
Summary
A speedup lasts only if something fails when it disappears. Use operation counts where the fix reduces work you can count. Use ratios against a kept baseline where the fix is algorithmic. Use saved-run comparisons on stable hardware to catch gradual drift. Compare minimums, leave generous margins, assert on correctness, and run timing tests in a separate job from your unit tests.
Exercise
A teammate writes this guard: assert best_time(process, data) < 0.005. It passes locally but fails about one run in five on the CI server. Name two changes that would make the guard more reliable, and say why each helps.
Show answer
First, replace the absolute limit with a ratio against a kept slow reference implementation, such as assert fast * 20 < slow. Both functions run on the same machine in the same run, so hardware speed cancels out. Second, if no reference exists, count a deterministic quantity instead, such as cache misses or calls to the expensive function. A count does not depend on the clock. If the timing must stay, take the minimum of several repeats and leave a larger margin, because noise only ever adds time.
Exercise
You change fib to use @lru_cache(maxsize=32) and the call counter test assert info.misses == 61 for fib(60) still passes on the first run, but the test that calls fib(60) twice in a row starts to fail on its second call's miss count. What is the likely cause, and how would you fix the test?
Show answer
With maxsize=32, the cache holds only 32 entries, so older results are evicted. The second call to fib(60) finds some of its needed values missing and recomputes them, which adds misses. Either restore an unbounded cache (maxsize=None) if memory allows, or change the guard to assert a bound that matches the intended behavior. Also call fib.cache_clear() at the start of each test so earlier calls do not change the count.