Sub topic 1
Why Benchmark, and Why Criterion
Prerequisites
Assume you know basic Rust syntax, functions, closures, Cargo commands, and Cargo.toml. A benchmark measures how long code takes to run. It helps you detect regressions, compare implementations, and check whether an optimization actually works.
Rust’s built-in test harness is useful for correctness tests, but timing one function once is unreliable. Operating-system scheduling, CPU frequency changes, and other processes add noise. Criterion runs warm-up iterations, collects many samples, and applies statistical analysis. It also detects changes against earlier results and creates HTML reports.
Setting Up Cargo with a Criterion Bench Target
Add Criterion as a development dependency and disable Cargo’s default benchmark harness. Criterion supplies its own main function.
[dev-dependencies]
criterion = { version = "0.5", features = ["html_reports"] }
[[bench]]
name = "fib_bench"
harness = falseCreate benches/fib_bench.rs:
use criterion::{black_box, criterion_group, criterion_main, Criterion};
fn fibonacci(n: u64) -> u64 {
match n {
0 | 1 => 1,
n => fibonacci(n - 1) + fibonacci(n - 2),
}
}
fn bench_fib(c: &mut Criterion) {
c.bench_function("fib 20", |b| {
b.iter(|| fibonacci(black_box(20)))
});
}
criterion_group!(benches, bench_fib);
criterion_main!(benches);Run it with:
cargo benchWriting Your First Benchmark
bench_function gives the benchmark a name and receives a closure that configures it. The closure passed to iter is the measured operation. Criterion calls that closure repeatedly, rather than relying on one noisy timing.
Keeping the Compiler Honest with `black_box`
black_box hides a value from compiler optimization. Without it, the compiler might know that the input is always 20 and simplify or precompute work. Use it for inputs and, when appropriate, outputs that must remain part of the measurement.
> callout note > Benchmark the work users care about. Keep file loading, data generation, and other setup outside the timed closure unless setup is part of the question.
Exercise
Why does this benchmark use black_box(20) instead of passing 20 directly?
Show answer
It prevents the compiler from assuming the input and removing or precomputing the measured work.