How to embed and customize a Benched report in Sphinx

This guide shows you how to include a Benched report inline and transform its data during a Sphinx build.

Embed a report inline

Add the directive where you want the report to appear in a reStructuredText page:

.. benched:: ../benchmark-results
   :view: trend
   :metric: median
   :x-axis: version

Use the same directive in a MyST Markdown page:

```{benched} ../benchmark-results
:view: trend
:metric: median
:x-axis: version
```

Both forms render the interactive report directly in the page. This documentation’s generated example data is embedded below. Sphinx reports inherit the surrounding page’s light or dark theme by default.

Compare implementations from one pytest run

If your benchmark takes a solver parameter, select one implementation as the baseline. From the project root, check the comparison you want to publish:

benched compare latest --results-dir benchmark-results --baseline solver=mosek_qp

Embed the same run with a path relative to the Sphinx page:

.. benched-comparison:: ../benchmark-results
   :baseline: solver=mosek_qp

Each row compares a contender with the baseline at the same values of the remaining parameters. The ratio divides the contender value by the baseline value. Benched shows which measurements lack a baseline and why a metric is unavailable.

The default is the median from the latest successful run. Use :selector: with a run ID to pin published results, :metric: to choose another statistic such as mean or ops, and :benchmark: to filter benchmark IDs, node IDs, or names with a glob. For a paired effect and statistical verdict from BenchX, see How to embed a BenchX comparison.

To publish the installed versions of the libraries you benchmark, list their Python distribution names in the suite’s pyproject.toml before recording the run.

[tool.benched]
packages = ["pandas", "polars"]

Pytest reads the versions from its environment. A missing distribution stops the run before measurement. The table shows the saved versions and the suite’s Git revision, including whether the checkout had local changes. Keep implementation parameters stable (for example, pandas) so results from library upgrades appear in the same series.

Publish a standalone pandas and Polars comparison

This table reads a committed pytest-benchmark run. The recorded suite timed the bound Series.sum method at three input sizes.

Run dba5029bc6f64772bf62a5cf33d13cab compared with implementation=pandas

Benchmark

size

implementation

implementation=pandas (median)

Contender (median)

Ratio

test_series_sum.py::test_series_sum

1000

polars

2.084e-06 seconds

1.67e-07 seconds

0.0801×

test_series_sum.py::test_series_sum

100000

polars

8.292e-06 seconds

6.042e-06 seconds

0.729×

test_series_sum.py::test_series_sum

1000000

polars

7.871e-05 seconds

7.558e-05 seconds

0.96×

Packages: pandas 3.1.1, polars 2.2.0

Suite revision: 535c1ec0ceb5f6ab33646677e7db4bc2f4691a51

To record a new run, install Benched, pandas, and Polars in the benchmark environment. The pytest suite now times the same function as the BenchX pyperf example. Both timers include the lookup of the prepared series and the call to sum(). Pytest checks the returned sum after timing. From docs/examples/pytest, run:

benched run
benched compare latest --baseline implementation=pandas

Commit the new JSON under benchmark-results/ and set :selector: to its run ID when you want to publish it. The documentation build needs only Benched, Sphinx, and the saved results. Shared workload · Pytest benchmark · Suite configuration

Keep an embedded report compact

Preselect filters with directive options, then list controls that readers should not change in :hide-controls::

.. benched:: ../benchmark-results
   :view: trend
   :metric: median
   :x-axis: version
   :benchmark: tests/test_parse.py::test_parse|size=100
   :machine: linux,macos
   :python: 3.11,3.12
   :memory: 16,32
   :hide-controls: view,metric,x-axis,benchmark,machine,python,memory

Hidden controls do not disable their selections. Use :theme: light or :theme: dark to override the surrounding page; the default is inherit.

:benchmark: must be one exact benchmark ID because it selects the benchmark shown by the component. When embedding a results directory, use a separate glob to reduce the data compiled into the static report:

.. benched:: ../benchmark-results
   :view: trend
   :benchmark-filter: tests/test_parse.py::*
   :benchmark: tests/test_parse.py::test_parse|size=100

For a partial history, select the newest successful measurement independently for each benchmark:

.. benched:: ../benchmark-results
    :selector: latest-per-benchmark
    :view: trend

latest-per-benchmark must be the only selector. Existing benchmark, group, and parameter filters are applied before measurements are coalesced.

To keep one definition shared between the command line and documentation, name a preset in pyproject.toml and reference it with :preset::

[tool.benched.reports.solver]
benchmark = "*test_solver*"
metric = "median"
view = "trend"
latest_per_benchmark = true
.. benched:: ../benchmark-results
   :preset: solver

A preset may carry benchmark, metric, view, and either latest or latest_per_benchmark. The preset’s benchmark glob becomes :benchmark-filter:, and latest_per_benchmark becomes :selector: latest-per-benchmark. Options given explicitly on the directive override preset values. The same preset drives benched report --preset solver. Aliases declared in [tool.benched.aliases] are applied before reports are compiled, so renamed benchmarks keep one series.

Benched registers local report files and stored runs with Sphinx. Incremental builds therefore regenerate embedded report data after those inputs change. Remote fsspec sources are read when Sphinx rebuilds the document, but cannot notify Sphinx about external changes.

This live example preselects two machines, two Python versions, and two memory buckets while omitting their controls:

Match the surrounding Sphinx theme

Inherited reports automatically match Furo, Fuma, Sphinx Awesome, PyData, and Shibuya. No theme-specific Benched configuration is required. Benched uses the theme’s semantic colors for chart accents, grid lines, controls, surfaces, and text, and redraws charts when those colors change.

  • Furo: --color-* colors; body[data-theme] mode.

  • Fuma: --color-fd-* colors; root light / dark classes.

  • Sphinx Awesome: --color-* colors; root dark class.

  • PyData: --pst-color-* colors; root data-theme / data-mode attributes.

  • Shibuya: --sy-c-* colors; root light / dark classes.

The host’s selected mode takes precedence over background brightness and the OS color preference. In automatic mode, reports follow the theme’s resolved colors and OS preference. Unknown themes fall back to the surrounding background and color scheme. Standalone reports keep their own theme selection.

Override any inferred color from your documentation CSS:

benched-report {
  --benched-accent-color: #7c3aed;
  --benched-grid-color: #d4d4d8;
  --benched-muted-color: #71717a;
  --benched-surface-color: #ffffff;
  --benched-text-color: #18181b;
}

These overrides take precedence over detected theme colors when the report uses :theme: inherit. Use selectors from your Sphinx theme when an override should differ between light and dark modes. Modern CSS colors such as oklch() and color-mix() are supported when the browser supports them.

Use :theme: light or :theme: dark to opt out of host theme matching for an individual report.

Connect a report transformer

Add a callback and Sphinx setup function to conf.py:

from benched.model import Report


def customize_benchmarks(app, report: Report, options: dict[str, str]):
    data = report.to_dict()
    data["benchmarks"] = [
        benchmark
        for benchmark in data["benchmarks"]
        if not benchmark["name"].startswith("internal_")
    ]
    data["warnings"].append("Internal benchmarks are hidden in this documentation.")
    return data


def setup(app):
    app.connect("benched-process-report", customize_benchmarks)

The callback receives the compiled Report and current directive options. Return a Report, a report dictionary, or None to keep the original. Benched validates a replacement against the report model before writing it.

The event runs after Benched loads report JSON or compiles stored runs and before it writes _static/benched/reports/*.json. Benchmark execution is never part of the Sphinx build.

Apply options conditionally

Use the options argument when different directives need different presentation:

def customize_benchmarks(app, report, options):
    data = report.to_dict()
    if options.get("view") == "overview":
        data["warnings"].append("Overview values are documentation-specific.")
    return data

Only the first event listener that returns a non-None value supplies the replacement report. Keep shared transformations in one callback when several adjustments must be composed.