Benchmarks
suggest changeA benchmark measures how long a piece of code takes to run, so you can compare two implementations or check that a change didn't make things slower. It answers "which of these is faster, and by how much?". A profiler answers a different question, "where does my program spend its time?". Profile first to find the hot spot, then benchmark the alternatives for that hot spot. See Using cProfile for profiling.
This article covers:
- timing code with
time.perf_counter() - the
timeitmodule:timeit(),repeat(),Timer.autorange() python -m timeiton the command line- a small harness for comparing several functions
- measuring how speed changes with input size
- common mistakes that produce wrong numbers
- summarizing results with
statistics - third-party tools:
pyperfandpytest-benchmark
All examples were run with Python 3.13 on Windows. Timings depend on your machine, OS, Python version and what else is running, so your numbers will differ. The machine used here was busy with other work, which makes the noise easy to see. Look at the ratios between results, not the absolute values.
Timing with time.perf_counter
The simplest benchmark reads a clock before and after the code. Use time.perf_counter(): it is the clock with the highest available resolution and it is monotonic, meaning it never goes backwards. time.time() is wall-clock time and can jump when the system clock is adjusted, so don't use it to measure durations.
import time
def work():
return sum(i * i for i in range(1_000_000))
start = time.perf_counter()
work()
elapsed = time.perf_counter() - start
print(f"work() took {elapsed:.3f} s")
start_ns = time.perf_counter_ns()
work()
print(f"work() took {(time.perf_counter_ns() - start_ns) / 1e6:.1f} ms")
for name in ("time", "perf_counter", "monotonic", "process_time"):
info = time.get_clock_info(name)
print(f"{name:13} resolution={info.resolution:.1e} monotonic={info.monotonic}")
work() took 0.088 s
work() took 124.2 ms
time resolution=1.0e-07 monotonic=False
perf_counter resolution=1.0e-07 monotonic=True
monotonic resolution=1.0e-07 monotonic=True
process_time resolution=1.0e-07 monotonic=True
The same function took 88 ms once and 124 ms the next time. A single measurement is not reliable: other processes, CPU frequency scaling, caches and the garbage collector all affect it. perf_counter_ns() returns an integer number of nanoseconds, which avoids floating-point rounding when you measure very short intervals.
time.process_time() counts only the CPU time used by your process. It ignores time spent sleeping or waiting for I/O, which is useful when you want to measure computation and leave out waiting.
A single perf_counter() measurement is fine for code that runs for seconds, like a whole script or a big batch job. For anything shorter, use timeit.
The timeit module
timeit runs a piece of code many times in a loop and returns the total time in seconds. Running it many times averages out clock resolution and small fluctuations. You can give it a callable or a string of source code:
import timeit
def join_words(words):
return " ".join(words)
words = ["hello"] * 1000
# 1. a callable (use a lambda to pass arguments)
t = timeit.timeit(lambda: join_words(words), number=10_000)
print(f"callable: {t:.3f} s total, {t / 10_000 * 1e6:.2f} us per call")
# 2. a statement string plus setup string
t = timeit.timeit('" ".join(words)', setup='words = ["hello"] * 1000', number=10_000)
print(f"string: {t:.3f} s total")
# 3. a statement string that uses names from this module
t = timeit.timeit("join_words(words)", globals=globals(), number=10_000)
print(f"globals: {t:.3f} s total")
callable: 0.059 s total, 5.93 us per call
string: 0.057 s total
globals: 0.055 s total
Key points:
numberis how many times the statement runs. The result is the total time for all runs, so divide bynumberto get time per call.setupruns once before the timing starts and is not included in the result. Use it to create input data and import modules.- A string statement runs in its own namespace. It can't see your variables unless you create them in
setupor passglobals=globals(). - A lambda adds the cost of one extra function call (tens of nanoseconds). That matters only when the code being measured is itself just a few nanoseconds.
The default number is 1,000,000, which is far too many for slow code, so always pass it explicitly or use autorange().
repeat, min and autorange
timeit.repeat() runs the whole timeit() measurement several times and returns a list of totals. Report the minimum. Background activity can only make code slower, never faster, so the fastest run is closest to the true cost of the code. Higher values mostly tell you how much interference there was.
Timer.autorange() picks number for you: it tries 1, 2, 5, 10, 20, 50, ... loops until one measurement takes at least 0.2 seconds. It returns (number, total_time).
import timeit
stmt = "sorted(data)"
setup = "import random; random.seed(1); data = [random.random() for _ in range(10_000)]"
times = timeit.repeat(stmt, setup, repeat=5, number=200)
print([round(t, 4) for t in times])
best = min(times)
print(f"best: {best / 200 * 1e3:.3f} ms per call")
timer = timeit.Timer(stmt, setup)
number, total = timer.autorange()
print(f"autorange picked number={number}, took {total:.3f} s")
[0.2708, 0.2299, 0.2952, 0.2879, 0.2717]
best: 1.149 ms per call
autorange picked number=200, took 0.334 s
The 5 runs vary by almost 30%, which is why one measurement is not enough. timeit.Timer is the class behind the convenience functions. Create one when you want to call autorange(), timeit() and repeat() on the same statement.
timeit on the command line
python -m timeit is the quickest way to try out a one-liner. It chooses the loop count automatically, repeats 5 times and prints the best time per loop in a readable unit:
python -m timeit '"-".join(map(str, range(100)))'
python -m timeit -s 'd = {i: i for i in range(1000)}' 'd[500]'
python -m timeit -u msec -s 'import random' -s 'data = [random.random() for _ in range(10_000)]' 'sorted(data)'
python -m timeit -v -n 1000 'x = [0] * 100'
python -m timeit 'for i in range(10):' ' x = i * 2'
50000 loops, best of 5: 6.03 usec per loop
10000000 loops, best of 5: 25.8 nsec per loop
200 loops, best of 5: 0.986 msec per loop
raw times: 288 usec, 273 usec, 197 usec, 305 usec, 194 usec
1000 loops, best of 5: 194 nsec per loop
2000000 loops, best of 5: 215 nsec per loop
The most useful options:
| Option | Meaning |
|---|---|
-s STMT |
setup code, not timed; may be given several times |
-n N |
number of loops per measurement (default: chosen automatically) |
-r N |
number of repeats (default 5) |
-u UNIT |
output unit: nsec, usec, msec or sec |
-v |
also print the raw total of each repeat |
-p |
use time.process_time() instead of perf_counter() |
Each extra argument after the statement is another line of code, which is how the last command times a multi-line for loop. On Windows cmd.exe use double quotes around arguments instead of single quotes. IPython and Jupyter have the same tool built in as %timeit; see timeit and timeit in IPython.
Comparing several implementations
Usually you have two or three ways to do the same thing and want to know which is fastest. Here is a small reusable harness. It first checks that all candidates return the same result (a fast wrong answer is worthless), then measures each one with autorange() and repeat() and prints them sorted, relative to the fastest:
import timeit
def concat_plus(n):
s = ""
for i in range(n):
s += str(i)
return s
def concat_join_list(n):
return "".join([str(i) for i in range(n)])
def concat_join_map(n):
return "".join(map(str, range(n)))
def bench(funcs, *args, repeat=5):
# sanity check: all candidates must agree
results = {f(*args) for f in funcs}
assert len(results) == 1, "functions return different results"
rows = []
for f in funcs:
timer = timeit.Timer(lambda: f(*args))
number, _ = timer.autorange()
best = min(timer.repeat(repeat=repeat, number=number)) / number
rows.append((f.__name__, best))
fastest = min(t for _, t in rows)
for name, t in sorted(rows, key=lambda r: r[1]):
print(f"{name:18} {t * 1e6:9.2f} us {t / fastest:5.2f}x")
bench([concat_plus, concat_join_list, concat_join_map], 10_000)
Two runs of the same script:
concat_join_map 532.44 us 1.00x
concat_join_list 728.16 us 1.37x
concat_plus 1458.37 us 2.74x
concat_join_map 894.12 us 1.00x
concat_join_list 955.17 us 1.07x
concat_plus 1761.64 us 1.97x
The order is the same both times, but the ratios moved quite a bit. That's typical on a busy machine. Run a benchmark several times before you trust a difference of less than about 10-20%, and don't draw conclusions from a single run.
The lambda is created inside the loop but called later by the timer. That's fine here because f is used immediately in the same iteration. If you collected the lambdas in a list and ran them afterwards, they would all refer to the last f.
Measuring how speed scales with input size
A result for one input size can hide the real story. Benchmark several sizes to see how the cost grows. Here membership in a list is O(n) while membership in a set is O(1) on average:
import timeit
print(f"{'n':>9} {'list (us)':>11} {'set (us)':>10}")
for n in (10, 1_000, 100_000):
items = list(range(n))
as_set = set(items)
target = n - 1 # worst case for the list: last element
t_list = min(timeit.repeat(lambda: target in items, number=1000, repeat=5)) / 1000
t_set = min(timeit.repeat(lambda: target in as_set, number=1000, repeat=5)) / 1000
print(f"{n:>9} {t_list * 1e6:>11.3f} {t_set * 1e6:>10.3f}")
n list (us) set (us)
10 0.116 0.041
1000 6.632 0.079
100000 790.779 0.041
With 10 items the difference hardly matters. With 100,000 items the set is about 20,000 times faster. Benchmark with realistic data sizes: an optimization that wins on tiny inputs can lose on large ones, and the other way around. Also pick realistic values. Searching for the first element of a list would make the list look as fast as the set.
Mistakes that give wrong numbers
Constant folding
The compiler evaluates expressions made only of literals ahead of time. Timing them measures nothing:
import timeit
import dis
# The compiler folds 2 ** 20 into a constant, so we time nothing
print(timeit.timeit("x = 2 ** 20", number=1_000_000))
print(timeit.timeit("x = b ** 20", setup="b = 2", number=1_000_000))
dis.dis(compile("x = 2 ** 20", "", "exec"))
0.02801710000494495
0.07823679997818545
0 RESUME 0
1 LOAD_CONST 0 (1048576)
STORE_NAME 0 (x)
RETURN_CONST 1 (None)
The bytecode shows that 2 ** 20 became the constant 1048576. Put inputs in variables created in setup, so the computation actually happens at run time. The dis module lets you check what the statement compiles to.
Code that changes its own input
setup runs once per repeat, not once per loop. If the statement modifies the data, every loop after the first sees different data. Sorting in place is the classic example: only the first run sorts random data, and the rest sort an already-sorted list, which is much faster:
import timeit
setup = "import random; random.seed(0); data = [random.random() for _ in range(100_000)]"
# Wrong: list.sort() sorts in place. Only the first of the 20 runs
# sorts random data; the other 19 sort an already sorted list.
wrong = min(timeit.repeat("data.sort()", setup, number=20, repeat=5)) / 20
# Right: sort a fresh copy every time, and measure the copy separately
right = min(timeit.repeat("data[:].sort()", setup, number=20, repeat=5)) / 20
copy = min(timeit.repeat("data[:]", setup, number=20, repeat=5)) / 20
print(f"in place (wrong): {wrong * 1e3:6.2f} ms")
print(f"copy + sort: {right * 1e3:6.2f} ms")
print(f"copy alone: {copy * 1e3:6.2f} ms")
print(f"sort estimate: {(right - copy) * 1e3:6.2f} ms")
in place (wrong): 1.43 ms
copy + sort: 16.15 ms
copy alone: 0.42 ms
sort estimate: 15.73 ms
The wrong version reports sorting as 11 times faster than it really is. The same problem shows up with list.pop(), dict.clear(), consuming an iterator or a generator, and reading a file object. A file object is empty after the first read.
Caches and warm-up
Memoized functions, re pattern caches, imports and disk caches all make the second call much cheaper than the first. A benchmark that calls a cached function measures a dictionary lookup:
import timeit
from functools import lru_cache
@lru_cache(maxsize=None)
def slow_square(n):
return sum(n for _ in range(n))
# Every call after the first is a cache hit
cached = min(timeit.repeat(lambda: slow_square(10_000), number=1000, repeat=5)) / 1000
uncached = min(timeit.repeat(lambda: slow_square.__wrapped__(10_000), number=100, repeat=5)) / 100
print(f"cached: {cached * 1e6:8.3f} us")
print(f"uncached: {uncached * 1e6:8.3f} us")
cached: 0.065 us
uncached: 347.123 us
Decide what you want to measure, the first call (cold) or a steady state (warm), and design the benchmark for that. timeit measures the warm case. To measure a cold start, such as import time or startup of a script, time a new process: python -X importtime -c "import json" shows import costs, which python -m timeit cannot measure.
The garbage collector is disabled
By default timeit turns off the cyclic garbage collector while it measures, to make results more repeatable. Code that allocates many container objects normally triggers collections, so the real cost is higher. Re-enable the collector in setup to include it:
import gc
import timeit
def make_objects():
return [[i] for i in range(10_000)]
t_default = min(timeit.repeat(make_objects, number=50, repeat=5))
t_gc = min(timeit.repeat(make_objects, setup="gc.enable()", number=50, repeat=5))
print(f"gc disabled (timeit default): {t_default:.4f} s")
print(f"gc enabled: {t_gc:.4f} s")
gc disabled (timeit default): 0.0275 s
gc enabled: 0.0315 s
Other things to watch for
- Too short a measurement. Each measurement should last at least tens of milliseconds.
autorange()handles this for you. - Different work. Make sure all versions produce the same result for the same input, as the
bench()harness above checks. - Unrealistic data. Sorted vs random input, short vs long strings, and hits vs misses can change which version wins.
- Debug builds and tracing. Running under a debugger, a coverage tool or a profiler slows code down unevenly. Benchmark in a normal interpreter.
- Laptops on battery. Power saving modes and thermal throttling change CPU speed between runs.
Summarizing results with statistics
The minimum is the best single number for comparing small snippets. For longer operations you may also want to know how much the timing varies. The statistics module gives you the rest:
import statistics
import timeit
def parse_ints(text):
return [int(x) for x in text.split(",")]
text = ",".join(str(i) for i in range(1000))
number = 1000
runs = [t / number * 1e6 for t in timeit.repeat(lambda: parse_ints(text), number=number, repeat=15)]
print(f"min {min(runs):7.2f} us")
print(f"median {statistics.median(runs):7.2f} us")
print(f"mean {statistics.mean(runs):7.2f} us")
print(f"stdev {statistics.stdev(runs):7.2f} us")
print(f"max {max(runs):7.2f} us")
min 69.70 us
median 79.95 us
mean 83.03 us
stdev 15.29 us
max 134.17 us
The mean is pulled up by a few slow outliers. The median is more robust and is a good choice when you want "typical" performance rather than "best possible". A standard deviation of 20% of the mean is a sign that the machine was busy. Close other programs and run the benchmark again before comparing small differences.
A reusable timer for larger blocks
For coarse measurements inside a real program, such as how long loading a file or building an index takes, a context manager and a decorator built on perf_counter() are handy:
import time
from contextlib import contextmanager
from functools import wraps
@contextmanager
def timed(label):
start = time.perf_counter()
try:
yield
finally:
print(f"{label}: {(time.perf_counter() - start) * 1e3:.1f} ms")
def timed_func(func):
@wraps(func)
def wrapper(*args, **kwargs):
with timed(func.__name__):
return func(*args, **kwargs)
return wrapper
@timed_func
def build_index(n):
return {str(i): i for i in range(n)}
with timed("load"):
data = [i * 2 for i in range(2_000_000)]
index = build_index(500_000)
print(len(data), len(index))
load: 103.1 ms
build_index: 165.3 ms
2000000 500000
This measures one run, so it's good for spotting which phase of a program is slow, but use timeit to compare alternatives.
pyperf
pyperf is the tool used to benchmark CPython itself. Compared with timeit it runs each benchmark in several separate worker processes, discards warm-up runs, reports the mean and standard deviation, warns when results are unstable and can save results to JSON for later comparison. Install it with pip install pyperf.
# bench_join.py
import pyperf
def join_list(n):
return "".join([str(i) for i in range(n)])
def join_map(n):
return "".join(map(str, range(n)))
runner = pyperf.Runner()
runner.bench_func("join_list", join_list, 1000)
runner.bench_func("join_map", join_map, 1000)
python bench_join.py --fast -o join.json
...........
WARNING: the benchmark result may be unstable
* the standard deviation (16.4 us) is 21% of the mean (79.1 us)
Try to rerun the benchmark with more runs, values and/or loops.
Run 'python.exe -m pyperf system tune' command to reduce the system jitter.
Use pyperf stats, pyperf dump and pyperf hist to analyze results.
Use --quiet option to hide these warnings.
join_list: Mean +- std dev: 79.1 us +- 16.4 us
...........
WARNING: the benchmark result may be unstable
* the standard deviation (14.8 us) is 21% of the mean (69.2 us)
Try to rerun the benchmark with more runs, values and/or loops.
Run 'python.exe -m pyperf system tune' command to reduce the system jitter.
Use pyperf stats, pyperf dump and pyperf hist to analyze results.
Use --quiet option to hide these warnings.
join_map: Mean +- std dev: 69.2 us +- 14.8 us
Unlike timeit, pyperf tells you when the numbers can't be trusted. --fast does fewer runs and is meant for quick checks. Leave it out, or use --rigorous, for final numbers. pyperf also has a timeit command that works like python -m timeit:
python -m pyperf timeit --quiet --fast -s "data = list(range(1000))" "sum(data)"
Mean +- std dev: 3.67 us +- 0.92 us
To check whether a change made code faster, save results before and after to two JSON files and run python -m pyperf compare_to before.json after.json. It shows the speedup and whether the difference is significant.
pytest-benchmark
If your project uses pytest, pytest-benchmark lets you write benchmarks as tests. Install it with pip install pytest-benchmark. Request the benchmark fixture and call it with the function and its arguments. It returns the function's result, so you can still assert on it:
# test_parse.py
import json
DATA = json.dumps([{"id": i, "name": f"user{i}"} for i in range(1000)])
def test_json_loads(benchmark):
result = benchmark(json.loads, DATA)
assert len(result) == 1000
def test_json_dumps(benchmark):
obj = json.loads(DATA)
result = benchmark(json.dumps, obj)
assert result == DATA
pytest -q --benchmark-columns=min,median,mean,stddev,rounds test_parse.py
.. [100%]
-------------------------------------------- benchmark: 2 tests --------------------------------------------
Name (time in us) Min Median Mean StdDev Rounds
------------------------------------------------------------------------------------------------------------
test_json_loads 265.5000 (1.0) 316.1000 (1.0) 492.6082 (1.10) 466.4319 (1.39) 3049
test_json_dumps 295.1000 (1.11) 335.8000 (1.06) 446.4249 (1.0) 335.6478 (1.0) 1431
------------------------------------------------------------------------------------------------------------
Legend:
Outliers: 1 Standard Deviation from Mean; 1.5 IQR (InterQuartile Range) from 1st Quartile and 3rd Quartile.
OPS: Operations Per Second, computed as 1 / Mean
2 passed in 2.19s
The numbers in parentheses are ratios relative to the best value in each column. Useful options: --benchmark-autosave stores results in .benchmarks/, --benchmark-compare compares against the last saved run, --benchmark-compare-fail=mean:10% fails the run if it got more than 10% slower, and --benchmark-skip runs the tests without timing them.
Guidelines
- Profile first, then benchmark the code that actually matters.
- Use
timeit(orpython -m timeit) for small snippets, never a singleperf_counter()pair. - Repeat measurements and report the minimum, or the median for longer operations.
- Check that every version gives the same result on realistic input, at realistic sizes.
- Keep setup out of the timed code, and make sure the timed code doesn't change its own input.
- Re-run before trusting differences smaller than 10-20%, and use pyperf when you need to know the result is stable.
- Benchmark on the Python version and kind of machine you deploy to. Results change between versions: CPython 3.11 made many common operations noticeably faster.