Sub topic 10
Tuning sample size and measurement time
This chapter assumes you can already write a Criterion benchmark with bench_function and Bencher::iter, and that you know how to read the console output. You should know that Criterion collects many samples, and that criterion_group! registers benchmark functions. Here you will learn which settings control how long a benchmark runs and how precise its result is.
What the defaults do
Criterion runs each benchmark in two timed phases.
- Warm-up. The function runs repeatedly for
warm_up_time(3 seconds by default). Criterion uses this phase to warm caches and the CPU's frequency state, and to estimate how long one iteration takes. - Measurement. Criterion collects
sample_sizesamples (100 by default). It picks the iteration counts so that all samples together take aboutmeasurement_time(5 seconds by default).
A sample is one timing of a batch of iterations. It is not a single call. In the default linear sampling mode, sample number i runs i * d iterations, where d is a step size Criterion chooses from the warm-up estimate. Later samples are longer than earlier ones. Criterion then fits a line through the (iteration count, total time) points, and the slope is the time per iteration.
The total number of iterations in the measurement phase is d * (1 + 2 + ... + N), which equals d * N * (N + 1) / 2 for N samples. With N = 100 that is d * 5050.
The two main knobs
| Setting | Default | Effect of raising it | Cost |
|---|---|---|---|
| `sample_size` | 100 | More data points for the regression and the bootstrap. Usually a tighter confidence interval. | Longer run, and a longer measurement time is needed to fit the samples. |
| `measurement_time` | 5 s | More iterations per sample. This averages out timer resolution and short noise bursts inside each sample. | Longer run. |
| `warm_up_time` | 3 s | A better iteration estimate and a more stable machine state before measuring. | Longer run. |
sample_size must be at least 10. Criterion panics on a smaller value, because the statistics need enough points to be meaningful.
The two settings are linked. The sample count and the time budget together decide the step d. If you raise sample_size and leave measurement_time alone, each sample gets fewer iterations. If you raise measurement_time and leave sample_size alone, each sample gets more iterations.
Configuring with criterion_group!
The plain form criterion_group!(benches, bench_fn) uses Criterion::default(). To change settings for every benchmark in the group, use the named form and supply a config expression.
use std::time::Duration;
use criterion::{black_box, criterion_group, criterion_main, Criterion};
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()
.sample_size(50)
.measurement_time(Duration::from_secs(10))
.warm_up_time(Duration::from_secs(1));
targets = bench_work
}
criterion_main!(benches);Each builder method returns a new Criterion, so you can chain them. The three required keys in the named form are name, config, and targets, and they must appear in that order.
The same builder works when you call it directly. Inside a benchmark function you can also tune a single benchmark group, which leaves the rest of the file alone:
use std::time::Duration;
use criterion::{black_box, criterion_group, criterion_main, Criterion};
fn slow_work(n: u64) -> u64 {
let mut total = 0u64;
for i in 0..n {
total = total.wrapping_add(black_box(i).wrapping_mul(31));
}
total
}
fn bench_slow(c: &mut Criterion) {
let mut group = c.benchmark_group("slow");
group.sample_size(10);
group.measurement_time(Duration::from_secs(8));
group.bench_function("loop 50M", |b| b.iter(|| slow_work(black_box(50_000_000))));
group.finish();
}
criterion_group!(benches, bench_slow);
criterion_main!(benches);Group-level settings apply only to benchmarks registered on that group. Use them when one slow benchmark needs different settings from the fast benchmarks around it.
Overriding from the command line
Criterion also reads flags after --. Flags on the command line win over values set in code, which is handy for quick experiments without editing the source.
# Run a short, rough pass while iterating on code
cargo bench -- --sample-size 20 --measurement-time 2 --warm-up-time 1
# Run only benchmarks whose name contains "fib", with more samples
cargo bench -- fib --sample-size 200The -- separates Cargo's arguments from the ones passed to the benchmark binary. A positional argument such as fib is a filter on benchmark names.
When the measurement time is too short
If the benchmark is slow, the time budget cannot fit the requested samples. Criterion cannot run fewer than one iteration per sample, so d cannot go below 1. Suppose one iteration takes 20 ms and you use the defaults. The smallest possible run is 1 * 5050 * 20 ms, which is about 101 seconds. Criterion prints a warning like this:
Warning: Unable to complete 100 samples in 5.0s. You may wish to increase
target time to 101.0s, enable flat sampling, or reduce sample count to 10.The warning is not an error. The benchmark still runs and takes as long as it needs, so the run silently exceeds your 5 second budget. You have three ways to respond.
- Reduce
sample_size. With 10 samples, the minimum cost is55 * 20 ms = 1.1 s, which fits in 5 seconds. You get less data, so expect a wider confidence interval. - Increase
measurement_time. This keeps 100 samples but costs more wall-clock time per run. It is the right choice when you need tight intervals and can afford the time. - Switch to flat sampling. Every sample then runs the same number of iterations instead of a growing number. The total cost is lower, so long benchmarks fit the budget more easily.
Flat sampling is set per group:
use std::time::Duration;
use criterion::{black_box, criterion_group, criterion_main, Criterion, SamplingMode};
fn heavy(n: u64) -> u64 {
(0..n).fold(0u64, |acc, i| acc.wrapping_add(black_box(i).wrapping_mul(i)))
}
fn bench_heavy(c: &mut Criterion) {
let mut group = c.benchmark_group("heavy");
group.sampling_mode(SamplingMode::Flat);
group.sample_size(20);
group.measurement_time(Duration::from_secs(15));
group.bench_function("fold 100M", |b| b.iter(|| heavy(black_box(100_000_000))));
group.finish();
}
criterion_group!(benches, bench_heavy);
criterion_main!(benches);Flat sampling gives up one thing. The linear mode can separate fixed per-sample overhead from per-iteration cost, because its sample sizes vary. Flat mode cannot, so it is less able to correct for that overhead. For benchmarks that take milliseconds or more per iteration, the overhead is negligible and flat sampling is the better choice.
The opposite problem is less visible. A very fast function, such as a few nanoseconds, gets a huge step d so that each sample lasts long enough to time reliably. That is why Criterion can measure operations far shorter than the timer's resolution.
Statistical settings you rarely change
These settings affect the analysis, not the sampling.
nresamples(default 100,000) is the number of bootstrap resamples used to compute confidence intervals. Lower values make analysis faster and the intervals slightly noisier.confidence_level(default 0.95) is the confidence level of the reported intervals.significance_level(default 0.05) is the p-value threshold below which Criterion calls a difference from the previous run statistically significant.noise_threshold(default 0.01) is the smallest relative change, 1%, that Criterion treats as a real change. Smaller changes are reported as "Change within noise threshold" even if they are statistically significant.
On a noisy machine you often get more value from raising noise_threshold to 0.03 or 0.05 than from collecting more samples. More samples reduce random error, but they do not remove a systematic shift such as another process using the CPU. Raising the threshold stops Criterion from reporting that shift as a regression.
use criterion::Criterion;
fn configured() -> Criterion {
Criterion::default()
.sample_size(100)
.noise_threshold(0.03)
.significance_level(0.01)
.confidence_level(0.99)
}
fn main() {
let _c = configured();
}Passing such a function as the config expression in criterion_group! keeps the settings in one place for the whole file.
Choosing values in practice
- Start with the defaults. They suit functions that take microseconds up to a few hundred microseconds.
- Shorten while developing. Use
--sample-size 20 --measurement-time 2for a fast feedback loop. Treat the numbers as rough. - Lengthen for results you will report or gate on. Use more
measurement_timeand keepsample_sizeat 100 or higher. - Handle slow functions on their own. Put them in a separate group with a small
sample_sizeand flat sampling, so they do not force a long budget on everything else. - Fix the cause when results are unstable. A wide interval across runs usually points to noise from the machine, not too few samples. The pitfalls chapter covers the causes.
Exercise
A benchmark takes about 20 ms per iteration. You use the default settings (100 samples, 5 s measurement time, linear sampling). Why does Criterion warn, and what is the smallest total measurement time it would need? Give two ways to remove the warning.
Show answer
In linear mode the samples run 1, 2, ..., 100 times the step d, and d cannot go below 1. The smallest run is 1 + 2 + ... + 100 = 5050 iterations, and 5050 * 20 ms is about 101 s, which is far above the 5 s budget, so Criterion warns that it cannot finish in the target time. You can remove the warning by raising measurementtime to about 101 s, by lowering samplesize (10 samples need only 55 iterations, about 1.1 s), or by using SamplingMode::Flat on the group.
Exercise
You run cargo bench -- --sample-size 20 on a file whose criteriongroup! config sets `.samplesize(200)`. Which value is used, and what changes in the result compared with the 200-sample run?
Show answer
The command-line value, 20, takes precedence over the value set in code. With fewer samples the regression and bootstrap have less data, so the confidence interval is usually wider, and each sample gets more iterations if the measurement time is unchanged.