pytest-codspeed

4.3.0 · active · verified Fri Apr 10

pytest-codspeed is a pytest plugin that integrates performance benchmarking into your Python test suite. It allows developers to measure and track the performance of their code, providing support for CPU simulation, wall-time, and memory usage measurements. The library is actively maintained with frequent releases, currently at version 4.3.0, and aims to provide highly consistent benchmark results, especially when run in CI environments.

Warnings

Install

Imports

Quickstart

This example demonstrates two common ways to create benchmarks with pytest-codspeed: using the `@pytest.mark.benchmark` decorator to measure an entire test function, and using the `benchmark` fixture for precise control over the code block to be measured within a test. Benchmarks can be run locally using `pytest --codspeed`.

import pytest

def sum_squares(arr):
    """Sum the squares of the numbers in an array."""
    total = 0
    for x in arr:
        total += x * x
    return total

@pytest.mark.benchmark
def test_sum_squares_full_function():
    """Benchmark an entire test function using the decorator."""
    # This entire function's execution will be measured
    assert sum_squares(range(1000)) == 332833500

def mean(data):
    return sum(data) / len(data)

def test_mean_performance_fine_grained(benchmark):
    """Benchmark a specific part of a test function using the fixture."""
    data = list(range(1_000_000)) # Setup not measured
    
    # Only the lambda function's execution will be measured
    result = benchmark(lambda: mean(data))
    assert result == 499999.5

# To run locally: pytest your_test_file.py --codspeed

view raw JSON →