Sub topic 3
Reporting Throughput and Reliable Criterion Results
Assume you know basic Rust, Cargo, and benchmark functions. This chapter focuses on interpreting and comparing measurements.
Reporting Throughput
A duration tells you how long one operation takes. Throughput tells you how much work the benchmark processes per second. Criterion can report bytes or logical elements:
use criterion::{
black_box, criterion_group, criterion_main, BenchmarkId, Criterion, Throughput,
};
fn checksum(data: &[u8]) -> u64 {
data.iter().map(|&byte| byte as u64).sum()
}
fn bench_checksum(c: &mut Criterion) {
let mut group = c.benchmark_group("checksum");
for size in [1024usize, 4096, 16_384] {
let data = vec![1u8; size];
group.throughput(Throughput::Bytes(size as u64));
group.bench_with_input(BenchmarkId::from_parameter(size), &data, |b, data| {
b.iter(|| checksum(black_box(data.as_slice())))
});
}
group.finish();
}
criterion_group!(benches, bench_checksum);
criterion_main!(benches);Use Throughput::Elements when a byte count is not the useful unit, such as records or packets.
| Report | Best for |
|---|---|
| Bytes per second | Files, buffers, compression, parsing |
| Elements per second | Records, messages, or collection items |
Tuning Measurement
Criterion warms up the benchmark, collects samples, and analyzes their distribution. Increase measurement_time when results are noisy or the operation is very fast. Increase sample_size when you need more observations.
use std::time::Duration;
use criterion::{criterion_group, Criterion};
criterion_group! {
name = benches;
config = Criterion::default()
.sample_size(50)
.measurement_time(Duration::from_secs(10));
targets = bench_checksum
}Baselines and Change Detection
Save a known run, then compare later runs against it:
cargo bench -- --save-baseline before
cargo bench -- --baseline beforeCriterion reports estimated changes and whether the difference is statistically significant. Its HTML report also shows distributions and comparison charts.
Pitfalls and CI
Keep setup outside the timed closure when it is not part of the operation. Avoid allocating, logging, or reading changing external data during measurement. Run benchmarks on a quiet, consistent machine. CPU frequency scaling, background processes, and shared CI runners can add noise.
In CI, save or retrieve baselines deliberately and inspect Criterion's change output. A benchmark can detect regressions, but it should not fail the build from a single noisy sample without a review policy.
Exercise
Which throughput type should you use for a benchmark that processes 10,000 database records?
Show answer
Use Throughput::Elements(10_000), because records are the meaningful unit.