Sub topic 13
Using Benchmarks in Continuous Integration
Criterion can catch performance regressions before they reach your main branch, but only if you set it up with care. This chapter assumes you can write Criterion benchmarks with bench_function and iter, and that you know how --save-baseline and --baseline work. It also assumes you have used a CI service such as GitHub Actions. The examples use GitHub Actions, but the ideas carry over to other systems.
What CI can and cannot tell you
Running benchmarks in CI is harder than running tests there. A test gives the same answer every time. A benchmark gives a different number on every run, and the number depends on the machine.
Most hosted CI runners are virtual machines on shared hardware. Other jobs on the same host compete for CPU cache, memory bandwidth, and sometimes cores. CPU frequency scaling and the runner's hardware generation also vary. A benchmark that takes 100 µs on one run can take 130 µs on the next with no code change.
Two consequences follow:
- Absolute times from one CI run are not meaningful. A "fib 20 took 25 µs" result from last week cannot be compared with one from today if they ran on different machines.
- Relative comparisons can work, if the two measurements being compared run on the same machine, close together in time.
The rest of the chapter follows from that second point. Compare two builds in the same job, treat only large changes as real, and keep humans in the loop for borderline results.
Criterion reports results as files
Criterion does not fail a build when performance gets worse. The console prints Performance has regressed., but the process still exits with status 0. To gate a pull request, you must read Criterion's output files and decide yourself.
Criterion writes everything under target/criterion/. For a benchmark named fib 20, the layout looks like this:
| Path | Contents |
|---|---|
| `target/criterion/fib 20/new/estimates.json` | Statistics for the most recent run |
| `target/criterion/fib 20/base/estimates.json` | Statistics saved under the baseline named `base` |
| `target/criterion/fib 20/change/estimates.json` | Estimated relative change between the last two compared runs |
| `target/criterion/report/index.html` | HTML report (skipped with `--noplot`) |
For a benchmark in a group, such as fibonacci/10, the group name becomes a directory and the input is a subdirectory below it.
The change/estimates.json file is the one CI cares about. It holds a mean and a median entry. Each has a point_estimate and a confidence_interval with lower_bound and upper_bound. These values are fractions: 0.05 means 5% slower, and -0.05 means 5% faster.
Comparing the base branch and the pull request in one job
The most reliable layout runs both builds on the same runner, one after the other. Benchmark the base commit and save it as a baseline. Then benchmark the pull request commit and compare it against that baseline.
name: bench
on:
pull_request:
jobs:
bench:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: dtolnay/rust-toolchain@stable
- name: Benchmark the base commit
run: |
git checkout ${{ github.event.pull_request.base.sha }}
cargo bench --bench fib_bench -- --save-baseline base --noplot
- name: Benchmark the pull request
run: |
git checkout ${{ github.event.pull_request.head.sha }}
cargo bench --bench fib_bench -- --baseline base --noplot
- name: Check for regressions
run: python3 scripts/check_regression.py 0.10
- name: Upload report
if: always()
uses: actions/upload-artifact@v4
with:
name: criterion
path: target/criterionSome details in this workflow matter:
git checkoutdoes not touchtarget/, because Cargo's output directory is ignored by Git. The saved baseline therefore survives the switch to the pull request commit.--bench fib_benchlimits the run to your Criterion target. Without it,cargo bench -- --save-baseline basealso passes the flag to the default test harness of any library or binary target. That harness does not know the flag and exits with an "Unrecognized option" error.--noplotskips chart generation, which saves time in CI. The JSON files are still written.fetch-depth: 0is needed so the base commit is available locally.- The upload step uses
if: always()so you can still download the data when the regression check fails.
If the pull request adds the benchmark file itself, the base commit has no benchmark to run, and the first step fails. In that case there is nothing to compare, so skip the job for that pull request, or let the first run on the main branch establish the baseline.
Failing the build on a regression
The script below reads every change/estimates.json file and fails if any benchmark is confidently slower than a threshold you choose.
import json
import sys
from pathlib import Path
threshold = float(sys.argv[1]) if len(sys.argv) > 1 else 0.10
root = Path("target/criterion")
checked = 0
failures = []
for path in sorted(root.glob("**/change/estimates.json")):
mean = json.loads(path.read_text())["mean"]
point = mean["point_estimate"]
low = mean["confidence_interval"]["lower_bound"]
name = path.parent.parent.relative_to(root)
checked += 1
print(f"{name}: change {point:+.1%} (95% CI lower bound {low:+.1%})")
if low > threshold:
failures.append(str(name))
if checked == 0:
sys.exit("No comparison data found. Did the baseline run first?")
if failures:
sys.exit("Regression above {:.0%} in: {}".format(threshold, ", ".join(failures)))The script compares the lower bound of the confidence interval with the threshold, not the point estimate. A lower bound of +0.12 means that even the optimistic end of the interval is 12% slower. That makes a failure much less likely to be noise than a check on the point estimate alone.
A threshold of 10% is a reasonable starting point on shared runners. Run the workflow a few times on an unchanged commit and see how large the reported "changes" get. Set the threshold clearly above that spread. If an identical commit sometimes shows +8%, a 5% threshold produces false alarms and people will learn to ignore the check.
The script also exits with an error when it finds no files. Without that guard, a typo in the benchmark name or a failed baseline step would make the check pass silently. The paths in target/criterion are a Criterion implementation detail, so verify them against your Criterion version when you upgrade.
Reducing noise
You cannot remove noise from a shared runner, but you can reduce it. Use these steps roughly in order of payoff.
| Technique | Effect | Cost |
|---|---|---|
| Benchmark base and pull request in the same job | Both runs see similar machine conditions | Doubles benchmark time |
| Raise `sample_size` or `measurement_time` | Narrower confidence intervals | Longer runs |
| Use a dedicated or self-hosted runner | Removes neighbors and gives stable hardware | Infrastructure to maintain |
| Run only the benchmarks that matter | Shorter job, fewer false alarms | You must choose them |
| Repeat the comparison before failing | Filters out one-off spikes | Longer runs |
Command-line flags let you change settings for CI without editing the code. For example, cargo bench --bench fib_bench -- --sample-size 200 --measurement-time 10 gives a longer measurement than the defaults. You can also set a custom configuration with criterion_group! as in the earlier chapter on configuration. Keep the configuration the same for the baseline run and the comparison run. If you change it between the two, a difference in sample counts or timing can show up as a performance change.
Keeping baselines between runs
The same-job layout above rebuilds the baseline on every pull request. This is simple and reliable, but it spends time benchmarking the base commit again. Two alternatives trade accuracy for speed.
Cache the baseline. Run the benchmarks on the main branch after each merge, and store target/criterion in the CI cache keyed by the commit. Pull request jobs restore it and run only --baseline main. This halves the benchmark time, but the baseline was measured on a different runner at a different time. That brings back exactly the noise the same-job layout avoids. This approach works best with a self-hosted runner whose hardware stays the same.
Run benchmarks on a schedule. A nightly or weekly job on the main branch runs the full suite with generous settings and stores the results as artifacts. Nobody waits for it, so it can afford long measurement times. It catches slow drift that no single pull request would trigger, and you can inspect the HTML report when a trend looks wrong. The cost is that you find regressions after they merge.
Many teams combine both approaches. They run a quick, narrow comparison on pull requests, using a small set of important benchmarks and a loose threshold. A thorough scheduled run covers everything else.
Common problems
- The first step fails with "Unrecognized option". The flag reached the default test harness. Name your target with
--bench, as in the workflow above. - The check passes but nothing was compared. The baseline name differs between the two commands, or the baseline run failed. Keep the name in one place, and keep the zero-files guard in the script.
- Results flip between pass and fail on the same code. The threshold is inside the noise. Measure the spread on an unchanged commit and raise the threshold, or increase the measurement time.
- Different inputs produce different benchmark names. If a pull request renames a benchmark or changes its
BenchmarkId, Criterion treats it as a new benchmark with no baseline. It will not appear in the comparison, so a renamed benchmark can hide a regression. - Compile time dominates the job. Cache Cargo's registry and build output with a cache action to save the time spent building dependencies. Do not cache the
target/criteriondirectory between pull requests unless you intend to reuse a saved baseline. - Plots slow down the run. Pass
--noplotin CI and uploadtarget/criterionas an artifact only when you need the HTML reports.
Exercise
A CI job runs cargo bench -- --save-baseline base on the base commit, then cargo bench -- --baseline base on the pull request commit. The project has both a library and a Criterion bench target. The first command fails with "Unrecognized option: 'save-baseline'". What is the cause, and how do you fix it?
Show answer
The arguments after -- are passed to every benchmark target that Cargo builds, including the library's default test harness, which does not understand Criterion's flags. Select only the Criterion target with --bench, for example cargo bench --bench fib_bench -- --save-baseline base, and use the same form for the comparison run.
Exercise
Your regression check fails if the point estimate of the change is above +5%. On an unchanged commit, repeated runs show changes between -7% and +8%. Name two ways to make the check more trustworthy.
Show answer
Compare against a larger threshold chosen above the observed noise (for example 10% to 15%). Alternatively, compare the lower bound of the confidence interval instead of the point estimate, so that only changes you are confident about fail the build. Longer measurement time, a dedicated runner, and benchmarking base and pull request in the same job also reduce the spread.
Exercise
Why does the regression script exit with an error when it finds no change/estimates.json files, instead of just printing nothing and passing?
Show answer
If the baseline step failed, the baseline name was misspelled, or the benchmark was renamed, no comparison files exist. A script that passes on an empty result would report success without having checked anything. Failing loudly makes the missing comparison visible.