Sub topic 12
Common pitfalls and sources of noise
This chapter assumes you can already write a Criterion benchmark with bench_function, iter, and black_box, and that you have read a console report with its time interval and change line. It covers two kinds of problems. The first is measuring the wrong thing, where the number is stable but means nothing. The second is measuring the right thing with too much variation, where the number moves between runs for reasons unrelated to your code.
Measuring the wrong thing
Criterion reports whatever the closure takes to run. It cannot tell whether that matches what you meant to measure.
The optimizer removes your work
cargo bench builds with optimizations. The compiler may delete a computation whose result is never used, or evaluate it at compile time when its inputs are constants.
use criterion::{black_box, criterion_group, criterion_main, Criterion};
fn sum_to(n: u64) -> u64 {
(0..n).sum()
}
fn bench_sum(c: &mut Criterion) {
// The input is a constant, so the compiler may fold the whole call.
c.bench_function("sum naive", |b| b.iter(|| sum_to(1000)));
// black_box hides the value from the optimizer.
c.bench_function("sum black_box", |b| b.iter(|| sum_to(black_box(1000))));
}
criterion_group!(benches, bench_sum);
criterion_main!(benches);Whether the first benchmark is folded depends on the compiler version and the function. Treat these as warning signs:
- A time well under one nanosecond for a loop that runs hundreds of iterations.
- A time that does not change when you make the input ten times larger.
- Two different implementations reporting the same suspiciously small time.
black_box is a hint, not a guarantee. Use it on inputs so they look unknown to the compiler. Criterion's iter already passes the closure's return value through black_box, so you do not need to wrap the result. Return the value from the closure instead of discarding it with a trailing semicolon.
Newer Rust versions also provide std::hint::black_box. It serves the same purpose, and recent Criterion releases recommend it over their own re-export.
Setup and teardown are inside the timer
Anything inside the closure passed to iter is timed. Cloning an input, building a collection, or opening a file there inflates the result and hides the cost of the code you care about. Move one-time setup outside the closure. For setup that is needed on every iteration, such as a fresh unsorted vector for each sort, use iter_batched as in the earlier chapter.
Drop cost is a subtler case. With plain iter, the value your closure returns is dropped inside the timed region. If the output is a large Vec or a map with many allocations, you are timing deallocation as well as construction. Sometimes that is right, because your program pays for it too. When it is not, use iter_with_large_drop:
use criterion::{criterion_group, criterion_main, Criterion};
fn bench_build(c: &mut Criterion) {
c.bench_function("build vec of 100k", |b| {
b.iter_with_large_drop(|| (0..100_000u32).collect::<Vec<_>>())
});
}
criterion_group!(benches, bench_build);
criterion_main!(benches);iter_with_large_drop keeps every output alive until the timing loop finishes, then drops them all outside the timer. The cost is memory. The number of iterations in a sample times the size of one output must fit in RAM, so it is a poor fit for very large outputs.
The input is unrepresentative
A benchmark answers a question about the inputs you give it. Common traps:
- Tiny inputs. A sort of 10 elements says little about a sort of 10 million. Cache behavior and algorithmic complexity change with size. Use a group with several sizes.
- Perfect inputs. Sorted, all-equal, or all-zero data is often the best case. Branch predictors and caches work very well when every iteration sees the same data. If production data is irregular, benchmark irregular data.
- One input reused forever. Criterion runs your closure millions of times. The data stays hot in cache and the branches become perfectly predictable. A real workload may touch cold memory. If that matters, cycle through a large pool of inputs or use
iter_batchedto supply fresh ones. - Random inputs that change between runs. If you generate data with an unseeded random source, two runs measure different workloads, and Criterion may report a change that is only the data. Use a fixed seed or deterministic data.
Benchmarking the wrong build
Benchmarks run under the bench profile, which inherits from release. Do not time code with cargo run or a debug build and compare it to Criterion output. If you changed [profile.release] or [profile.bench] settings such as opt-level, lto, or codegen-units, remember that benchmarks inherit them. A fair comparison with the production binary needs the same settings.
Also check what the benchmark links against. Benchmarks in benches/ can only call your crate's public API. If a function is small and cross-crate inlining differs from the call site in production, the numbers may differ from what the real program sees.
Sources of noise
Noise is variation that comes from the machine, not from your code. Criterion's statistics reduce it but cannot remove it.
| Source | Typical symptom | Mitigation |
|---|---|---|
| Other processes (browser, indexer, compiler) | Many outliers, wide interval | Close other programs, rerun |
| CPU frequency scaling and boost | Time drifts between benchmarks | Use a fixed performance governor |
| Thermal throttling | Later benchmarks look slower | Let the machine cool, shorten runs |
| Core migration and shared caches | High variance between runs | Pin the process to one core |
| Shared CI runners and virtual machines | Large run-to-run differences | Use dedicated hardware or compare within one job |
| Memory layout and alignment | Stable per build, shifts after unrelated code changes | Treat tiny differences as unreliable |
| Cold start and page faults | First sample slower | Keep the warm-up phase long enough |
On Linux you can reduce several of these at once:
# Prefer a fixed frequency, then pin the benchmark to core 2.
sudo cpupower frequency-set -g performance
taskset -c 2 cargo benchLaptops are the hardest case. Battery mode, boost clocks, and thermal limits all change speed during a run. Plug in power and avoid running other work in parallel.
Layout effects
Even on a quiet machine, an unrelated code change can move your function to a different address. Alignment of hot loops and cache-line placement affect speed by a few percent. If Criterion reports a 3% regression after a change that cannot plausibly touch the benchmarked path, suspect layout. Differences of this size are weak evidence.
Reading noise in Criterion's output
Criterion gives you several signals that the data is noisy.
- Outlier lines. The report counts outliers as mild or severe, using the distance from the quartiles. A few outliers are normal. Many severe outliers mean something disturbed the run.
- A wide confidence interval. If the lower and upper bounds differ by more than a few percent, small changes cannot be detected.
- Change detection. Criterion compares against the previous run with a significance test. The default significance level is 0.05, so about one in twenty comparisons of identical code can be flagged as a change by chance. The default noise threshold is 1%. Changes smaller than that are reported as within noise, even if statistically significant.
Both settings are adjustable:
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use std::time::Duration;
fn work(n: u64) -> u64 {
(0..n).sum()
}
fn bench_work(c: &mut Criterion) {
c.bench_function("sum 10000", |b| b.iter(|| work(black_box(10_000))));
}
criterion_group! {
name = benches;
config = Criterion::default()
.significance_level(0.01)
.noise_threshold(0.03)
.warm_up_time(Duration::from_secs(5));
targets = bench_work
}
criterion_main!(benches);A stricter significance level means fewer false alarms and more missed small changes. A higher noise threshold ignores small differences but also hides real small regressions. Choose them from the noise you measure on your machine, not by guessing.
Run an A/A test
The most useful check for noise is to compare the code against itself. Save a baseline, change nothing, and compare:
cargo bench -- --save-baseline a1
cargo bench -- --baseline a1If Criterion reports a significant change when nothing changed, your environment's noise is larger than your settings assume. Any result smaller than that noise is not trustworthy. Repeat this check when you move to a new machine or CI runner.
A practical checklist
- Wrap inputs in
black_boxand return the result from the closure. - Keep setup and large drops outside the timed region.
- Use realistic, deterministic, and varied inputs.
- Benchmark under the same profile as production.
- Close other programs, fix the CPU frequency, and pin the process if you can.
- Run an A/A test before trusting small differences.
- Treat changes within a few percent as unconfirmed until they repeat across runs.
Exercise
A benchmark of parse(&text) reports 0.4 ns per iteration, and the time stays the same when text grows from 1 KB to 1 MB. What is the most likely cause, and what two changes would you make?
Show answer
The compiler most likely removed the call or folded it, because the input is a constant or the result is unused, so almost no work is being timed. Pass the input through black_box (for example parse(black_box(&text))) and return the parsed result from the closure so it cannot be discarded. Then rerun and confirm that the time grows with the input size.
Exercise
You benchmark a function that builds and returns a HashMap with 50,000 entries. You want to measure only construction, not deallocation. Which Bencher method do you use, and what is its drawback?
Show answer
Use iter_with_large_drop. It stores all outputs from a sample and drops them after the timer stops. The drawback is memory use, since every output in a sample stays alive at once, so it is unsuitable when one output is very large.
Exercise
You run cargo bench -- --save-baseline a1 and then cargo bench -- --baseline a1 without changing any code. Criterion reports a 4% regression with a p-value below 0.05. What does that tell you, and what should you do before trusting a later 4% regression report?
Show answer
The environment's noise is large enough to produce apparent changes of at least 4%, so a 4% result from a real edit is not trustworthy. Reduce the noise (close other programs, fix the CPU frequency, pin the process, use quieter hardware) and repeat the A/A test. Raise the noise threshold only if the noise cannot be reduced.