Sub topic 5
How Criterion measures: warm-up, samples, and statistics
This chapter assumes you can run cargo bench on a Criterion target, as set up in the earlier chapters. It also assumes you know what Bencher::iter does and have a rough idea of mean, median, and standard deviation. Here you will learn what happens between c.bench_function(...) and the time: [...] line on your terminal. Knowing this helps you decide whether a result can be trusted.
The problem Criterion solves
Timing a function once is unreliable for two reasons:
- A single call to a fast function can take less time than the clock can resolve. Reading the clock also costs time.
- Caches, branch predictors, CPU frequency, and other processes all change the timing from run to run.
Criterion handles this by timing many iterations in one batch, repeating that batch many times, and applying statistics to the batch timings. It does this in four phases.
Phase 1: warm-up
Criterion first runs your closure repeatedly without recording results. It starts with a small iteration count and doubles it until the warm-up time has passed. The default is 3 seconds.
This phase has two purposes:
- It lets caches fill, lets the CPU leave a low-power state, and lets lazy initialization finish, so the measured samples are not skewed by a cold start.
- It gives a first estimate of the time per iteration. Criterion needs that estimate to choose batch sizes for the next phase.
If your function is very slow, one warm-up iteration may already exceed 3 seconds. Criterion still completes at least one run.
Phase 2: sampling
A sample is one timed batch of iterations. Criterion records the total iteration count and the total elapsed time for each sample. It does not time each iteration separately, so clock overhead is spread over the whole batch.
By default Criterion collects 100 samples within a target measurement time of 5 seconds. It chooses the batch sizes with one of two sampling modes:
| Mode | Iterations in sample *i* | Best for |
|---|---|---|
| Linear | *i* × *d*, for *i* = 1 to *n* | Fast benchmarks (microseconds or less) |
| Flat | the same count in every sample | Slow benchmarks (milliseconds or more) |
In linear mode, n is the sample size (100 by default). Criterion picks d from the warm-up estimate so that the total time of all samples is about the measurement time. The total iteration count is d × n(n + 1)/2. With n = 100 that is 5050 × d iterations.
The default mode is Auto. Criterion picks linear when the benchmark is fast enough to fit, and falls back to flat when linear sampling would need less than one iteration per early sample. You can force a mode on a group:
use criterion::{black_box, criterion_group, criterion_main, Criterion, SamplingMode};
fn heavy(n: u64) -> u64 {
(0..n).map(|x| x.wrapping_mul(x)).fold(0, |a, b| a.wrapping_add(b))
}
fn bench_heavy(c: &mut Criterion) {
let mut group = c.benchmark_group("heavy");
group.sampling_mode(SamplingMode::Flat);
group.sample_size(20);
group.bench_function("squares 5M", |b| b.iter(|| heavy(black_box(5_000_000))));
group.finish();
}
criterion_group!(benches, bench_heavy);
criterion_main!(benches);Flat sampling gives less information about per-iteration overhead, but it avoids samples whose early batches are too small to time reliably. Slow benchmarks are the case it is meant for.
Why varying batch sizes helps
Linear sampling produces points at different iteration counts. Each point is (iterations, total time). If every iteration costs t and each batch has a fixed overhead o, then total time ≈ t × iterations + o. Plotting that for many batch sizes gives a line. The slope is t, and the intercept absorbs o. This is the reason Criterion varies the batch size instead of repeating the same one.
Phase 3: analysis
After sampling, Criterion computes several statistics. Each is computed from the samples, not from individual iterations.
Slope, mean, and median
The headline estimate is the slope of the regression of total time against iteration count, as described above. For flat sampling there is no regression. Criterion reports the mean of the per-iteration times instead.
Criterion also reports these values:
- Mean and median of the per-iteration time of each sample.
- Standard deviation and MAD (median absolute deviation). MAD is a spread measure that outliers affect much less than the standard deviation.
- R² of the regression. A value near 1.0 means the points sit close to the fitted line. A low value, such as below 0.9, means the measurements were noisy or the workload was inconsistent.
Bootstrap confidence intervals
A single slope value would hide how uncertain it is, so Criterion computes a confidence interval with the bootstrap. It resamples the 100 observed samples with replacement, recomputes the statistic, and repeats this 100,000 times by default. The spread of those recomputed values gives the interval. The default confidence level is 95%.
The bootstrap needs no assumption that timings follow a normal distribution. That matters, because benchmark timings are usually skewed: they have a hard floor and a long tail of slow runs.
Outlier classification
Criterion also looks for samples that are unusually slow or fast. It uses Tukey's fences on the per-iteration times of the samples. Let Q1 and Q3 be the first and third quartiles, and IQR = Q3 − Q1:
- A mild outlier lies more than 1.5 × IQR beyond Q1 or Q3.
- A severe outlier lies more than 3 × IQR beyond them.
Outliers are reported as high or low. They are not removed from the data. The slope and the confidence interval are computed from all samples. The report is a warning that something disturbed the run.
What the console output shows
A typical result looks like this:
fib 20 time: [17.512 µs 17.563 µs 17.621 µs]
change: [-0.8123% -0.2204% +0.3817%] (p = 0.52 > 0.05)
No change in performance detected.
Found 6 outliers among 100 measurements (6.00%)
4 (4.00%) high mild
2 (2.00%) high severeThe three numbers in time: are the lower bound of the 95% confidence interval, the point estimate, and the upper bound. The middle value is the slope (or the mean, for flat sampling). A narrow interval means a precise estimate. It does not mean the estimate is the "true" speed on other hardware.
The change: line appears from the second run onward. Criterion stores the previous run's samples on disk, under target/criterion/. On the next run it compares the new samples with them. This comparison has two parts:
- A bootstrapped hypothesis test, a permutation t-test, gives a p-value. It tests whether the two sets of samples could plausibly come from the same distribution. The significance level is 0.05 by default.
- The size of the change must also exceed the noise threshold, which is 1% by default.
Criterion reports "Performance has regressed" or "Performance has improved" only when both conditions hold. If the p-value is low but the change is under the threshold, it reports "Change within noise threshold". If the p-value is high, it reports "No change in performance detected".
Common warnings
If Criterion cannot collect all samples in the target time, it prints a message like this:
Warning: Unable to complete 100 samples in 5.0s. You may wish to increase target time to 9.2s, enable flat sampling, or reduce sample count to 50.It means the benchmark is slow enough that 100 samples would need more time than allowed. Criterion then runs the minimum it can, which can take longer than 5 seconds. Follow one of its suggestions. For a slow function, reducing the sample size or using flat sampling is usually better than a long measurement time.
Adjusting the parameters
Each of the defaults above can be set in the configuration. The following example sets them explicitly, using the named form of criterion_group!:
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()
.warm_up_time(Duration::from_secs(1))
.measurement_time(Duration::from_secs(8))
.sample_size(200)
.confidence_level(0.99)
.significance_level(0.01)
.noise_threshold(0.02)
.nresamples(200_000);
targets = bench_work
}
criterion_main!(benches);This is what each setting changes:
warm_up_timesets the warm-up length.measurement_timeandsample_sizeset the sampling budget. More samples give a tighter interval and a longer run.confidence_levelwidens or narrows the reported interval. A 0.99 level gives a wider interval than 0.95.significance_levelis the p-value cutoff for change detection. A smaller value means fewer false alarms and more missed small changes.noise_thresholdis the minimum relative change that counts as real. Raise it on a noisy machine.nresamplesis the number of bootstrap resamples. It affects the smoothness of the interval, not the sample data.
Note that sample_size must be at least 10. Criterion panics with a smaller value.
Reading the results with some skepticism
The statistics describe the samples you collected. They cannot detect problems that affect every sample equally. Some things to keep in mind:
- A tight interval with a high R² means the measurements were consistent. It does not mean the benchmark measures what you intended. If the compiler removed your work, the result will be very consistent and also meaningless.
- The p-value comparison is against the last stored run. If the machine was busy during that run, a later run can look like an improvement.
- Two runs with different confidence intervals that overlap slightly are not automatically the same. Use the
change:line, which tests the difference directly. - The 5% significance level means that about 1 in 20 comparisons of identical code may report a change by chance. Rerun before acting on a borderline result.
Exercise
A benchmark uses the default settings: 100 samples, linear sampling, and a 5-second measurement time. The warm-up estimates 1 µs per iteration. Roughly how many iterations does Criterion choose for the batch increment d, and how many iterations does the last sample run?
Show answer
Total time is d × 5050 × 1 µs ≈ 5 s, so d ≈ 5 s / (5050 × 1 µs) ≈ 990. The last sample (i = 100) runs about 100 × 990 ≈ 99,000 iterations. The first sample runs about 990 iterations.
Exercise
Criterion reports "Found 8 outliers among 100 measurements" and your regression shows R² = 0.82. What does this suggest, and what is a sensible next step?
Show answer
The data is noisy. Some batches were disturbed, for example by other processes or CPU frequency changes, and the points do not lie close to a line. Close other programs, rerun on a quieter machine, and check whether the outlier count and R² improve before trusting the estimate. If they stay poor, increase the measurement time or investigate whether the benchmarked code has variable cost.