pytest-benchmark is a plugin for pytest that provides a `benchmark` fixture for benchmarking code. It automatically groups tests into rounds calibrated to the chosen timer, offering sensible defaults and automatic calibration for micro-benchmarks. As of version 5.2.3, it is actively maintained with regular major releases approximately once a year and several minor/patch releases.
pip install pytest-benchmarkVerified import paths — ran on the pinned version, not inferred.
Define a test function that accepts the `benchmark` fixture. Pass the function you wish to benchmark as the first argument to `benchmark()`. You can also pass positional and keyword arguments to the benchmarked function. Running `pytest` will execute the benchmarks and display a summary table.
Upgrade to Python 3.9+ or pin pytest-benchmark to <5.0.0.
Upgrade pytest to version 8.1 or newer, or pin pytest-benchmark to <5.1.0.
Prefer `benchmark(my_function, *args, **kwargs)` over `benchmark(lambda: my_function(*args, **kwargs))` for better accuracy, especially with very fast functions.
Ensure a stable, isolated environment. Minimize I/O and external dependencies in benchmarked code. Use `--benchmark-warmup` and `--benchmark-warmup-iterations` for JIT-heavy interpreters like PyPy. Consider `median` or `IQR` over `mean`/`stddev` for outlier-prone results.
When using a `setup` function with `benchmark.pedantic`, have the `setup` function return the arguments tuple/dict, and do not pass `args`, `kwargs`, or `iterations` separately to `pedantic`.
Create separate test functions for each distinct piece of code you want to benchmark. Use `pytest.mark.parametrize` for benchmarking the same function with different inputs.