Sub topic 13
Keeping the speedup: benchmarks in your workflow
This chapter assumes you can write pytest-style tests and have already timed code with timeit and time.perf_counter. A speedup you don't protect can quietly disappear. A later change, a dependency upgrade, or a "harmless" refactor can bring the slow behavior back, and nobody notices until users complain.
Why speedups regress
Correctness bugs fail tests. Performance bugs don't, because a function that is ten times slower still returns the right answer. A benchmark guard is a test that fails when speed drops below an agreed level. It turns the performance target from the start of this tutorial into something a machine checks.
Choose what to guard
Guard the code paths you already proved were hot spots with a profiler. Don't benchmark everything. Each guard costs run time and can produce false alarms.
| Guard type | What it checks | Strength | Weakness |
|---|---|---|---|
| Absolute budget | "Finishes in under 50 ms" | Easy to explain | Depends on the machine |
| Relative ratio | "At least 5x faster than the baseline" | Stable across machines | Needs a kept baseline function |
| Stored history | "No more than 20% slower than the last run" | Catches gradual drift | Needs storage and tooling |
Absolute budgets break when the continuous integration (CI) machine is slower than your laptop. Relative ratios are usually the best starting point, because both sides run on the same machine at the same moment.
A ratio guard you can run
The test below keeps the old slow algorithm as a baseline. It checks that the results match and that the fast version stays well ahead. Save it as test_dedupe_speed.py and run pytest.
import timeit
def dedupe_slow(items):
seen = []
out = []
for x in items:
if x not in seen:
seen.append(x)
out.append(x)
return out
def dedupe_fast(items):
seen = set()
out = []
for x in items:
if x not in seen:
seen.add(x)
out.append(x)
return out
def best_time(func, data, repeat=5, number=5):
runs = timeit.repeat(lambda: func(data), repeat=repeat, number=number)
return min(runs) / number
def test_dedupe_stays_faster_than_baseline():
data = list(range(2_000)) * 2
assert dedupe_fast(data) == dedupe_slow(data)
slow = best_time(dedupe_slow, data)
fast = best_time(dedupe_fast, data)
assert fast * 5 < slow, f"fast={fast:.5f}s slow={slow:.5f}s"Three details make the guard reliable:
- It takes the minimum of several repeats. Noise from other processes only makes runs slower, so the minimum is the least disturbed measurement.
- It checks correctness first. A function that returns the wrong answer quickly is not a speedup.
- It leaves a wide margin. The real gain is far above 5x, so ordinary variation will not trigger a failure.
Tools for stored history
For comparisons across commits, use a benchmark plugin such as pytest-benchmark. Install it with pip install pytest-benchmark. It provides a benchmark fixture, saves results, and can fail a run that is slower than a saved run by a set percentage. This is the stored-history approach from the table.
Where it fits in the workflow
When a guard fails, don't loosen the threshold right away. Profile the change first, as you did originally, and find out what got slower.
Common errors
- Benchmarking tiny inputs. Overhead dominates, and results are noisy.
- Tight absolute limits in CI. Shared runners vary a lot, so use ratios or generous margins.
- Running guards on every save. Keep them in a separate marker or CI stage if they are slow.
- Forgetting the baseline. Delete the slow function and the ratio check goes with it. Keep it in the test file.
Exercise
Why does the guard above use min(runs) instead of the average of the repeats, and why compare against a baseline instead of a fixed number of seconds?
Show answer
Noise from other processes can only add time, so the minimum is the least disturbed measurement, while an average is pulled up by slow outliers. A ratio against a baseline runs on the same machine at the same moment, so it holds on a slower CI runner, where a fixed time limit could fail with no real regression.