Sub topic 12
Common pitfalls and sources of noise
This chapter assumes you can write a Criterion benchmark with bench_function, use black_box, and read the console output. It covers the mistakes that produce wrong numbers and the system effects that make good numbers wobble.
Mistakes in the benchmark itself
These errors are in your code. Criterion cannot detect them, and the report looks normal either way.
The compiler removes the work
If the optimizer can see that a result is never used, or that the input is a constant, it may delete or precompute the work. The benchmark then reports a time near zero. Pass inputs through black_box, and return the result from the closure passed to iter so Criterion keeps it alive.
use criterion::{black_box, criterion_group, criterion_main, Criterion};
fn work(n: u64) -> u64 {
(0..n).sum()
}
fn bench_work(c: &mut Criterion) {
// Risky: constant input, the compiler may fold this at compile time.
c.bench_function("constant input", |b| b.iter(|| work(10_000)));
// Better: the input is opaque to the optimizer.
c.bench_function("black_box input", |b| b.iter(|| work(black_box(10_000))));
}
criterion_group!(benches, bench_work);
criterion_main!(benches);A time of well under a nanosecond for a loop over thousands of items is a strong sign that the work was optimized away.
Setup is inside the timed closure
Everything inside the closure given to iter is timed. If you build a vector, clone data, or open a file there, you measure that cost too. Move one-time setup outside the closure. For setup that must run fresh on every iteration, such as cloning a vector that the code under test mutates, use iter_batched so only the routine is timed.
Benchmarking the wrong profile
cargo bench builds with the release-like bench profile, so optimizations are on. Running a benchmark binary built in debug mode gives numbers that say little about production. Also check that the settings you ship with, such as lto or codegen-units, match what you benchmark.
Unrepresentative inputs
A sort benchmark on already sorted data, or a lookup that always hits the cache, can differ a lot from real use. Use several input sizes with a benchmark group, and choose data that resembles what the program sees.
Sources of noise
Even correct benchmarks vary between runs. The causes are mostly outside your code.
| Source | Effect | Mitigation |
|---|---|---|
| Other processes | Steal CPU time and cache | Close browsers, builds, and indexers |
| CPU frequency scaling and thermal throttling | Speed changes during the run | Use a fixed frequency governor, and let a laptop cool |
| Shared or virtualized hardware | Neighbors affect timing | Use a dedicated machine for important comparisons |
| Cold caches and memory layout | First iterations are slower | Rely on warm-up, and keep it enabled |
| Power saving on battery | Lower clock speeds | Plug in the machine |
Criterion's warm-up phase and its statistical analysis reduce these effects, but they do not remove them. A long run with a larger sample size helps, as the earlier configuration chapter showed.
Reading the outliers
The console output reports outliers, which are samples far from the rest. A few mild outliers are normal. Many severe ones mean the machine was busy. Rerun on a quieter system before trusting the result.
Change detection can report a difference that is not real
When Criterion compares a run against the previous one, it prints a message such as "Performance has regressed" when the p-value is below the significance level. Criterion's default noise threshold is 1%, and the default significance level is 0.05, so some false alarms are expected. If you change nothing and still see a change, the cause is noise. Treat small shifts, such as 2% or 3%, with suspicion unless they repeat across several runs.
A practical checklist
- Run on a quiet machine, plugged in, with unrelated programs closed.
- Run the same benchmark more than once and compare the results.
- Check that the time is plausible for the amount of work.
- Keep setup out of the timed closure.
- Save a baseline before a change, then compare against it after.
Exercise
A benchmark of a function that sums a slice reports 0.3 ns per iteration, and the slice has 100,000 elements. What is the most likely cause, and what two changes would you make?
Show answer
The optimizer most likely removed or precomputed the work, because summing 100,000 elements cannot take 0.3 ns. Pass the input through black_box, and return the result from the closure given to iter so it is not dead code.
Exercise
You benchmark a function that sorts a Vec in place. Inside iter you call data.clone() and then sort the clone. Why is the result misleading, and which Criterion method fixes it?
Show answer
The clone is timed together with the sort, so the result includes allocation and copying. Use iter_batched with the clone in the setup closure and the sort in the routine closure, so only the sort is measured.