Sub topic 2
How Criterion Measures: Warm-Up, Samples, and Statistics
Assume you know basic Rust, Cargo, closures, and Criterion setup with harness = false. This chapter focuses on interpreting results and designing fair measurements.
Warm-up, Samples, and Statistics
Criterion first runs a warm-up period. It uses this time to estimate how many iterations fit into a useful measurement interval. It then collects many samples, where each sample measures repeated executions of the benchmark.
Criterion analyzes the samples statistically instead of reporting one timing. It estimates a typical time, variation, and whether the result changed from a previous run.
Reading Reports
Console output commonly includes a median or mean estimate, a confidence interval, and a comparison with the previous result. A message such as change: -5% suggests the new code became faster, while change: +5% suggests it became slower. The report also indicates whether the change is statistically meaningful.
With the html_reports feature enabled, Criterion writes interactive reports under target/criterion/. Open the benchmark's HTML report to inspect distributions, confidence intervals, and comparisons between runs.
Comparing Inputs
Use a benchmark group when the same operation needs several inputs. BenchmarkId gives each input a distinct name, so the report can show how runtime changes with input size.
use criterion::{
black_box, criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion,
};
fn bench_sort(c: &mut Criterion) {
let mut group = c.benchmark_group("sort");
for size in [100usize, 1_000] {
group.bench_with_input(BenchmarkId::from_parameter(size), &size, |b, &size| {
b.iter_batched(
|| (0..size as u32).rev().collect::<Vec<_>>(),
|mut values| {
values.sort();
black_box(values);
},
BatchSize::SmallInput,
)
});
}
group.finish();
}
criterion_group!(benches, bench_sort);
criterion_main!(benches);Excluding Setup with `iter_batched`
iter_batched takes a setup closure, a timed operation closure, and a batch-size policy. Criterion runs the setup closure separately, then measures the operation closure. In the example, creating and filling the vector is setup; sorting is the measured work.
This separation prevents input construction from hiding the cost of the operation you want to compare.
Exercise
Why use BenchmarkId when benchmarking several input sizes?
Show answer
It gives each size a distinct benchmark name, making the results easy to compare.