Sub topic 3
Writing Your First Benchmark
This chapter assumes you can read basic Rust, use closures, and edit Cargo.toml. It also assumes you have already added Criterion as a dev-dependency. You will write a benchmark for a small function and run it.
Declaring the bench target
Criterion replaces Rust's built-in test harness. It supplies its own main function, so Cargo must not generate one. You turn the default harness off with harness = false in the bench target.
[dev-dependencies]
criterion = { version = "0.5", features = ["html_reports"] }
[[bench]]
name = "fib_bench"
harness = falseThe name must match a file at benches/fib_bench.rs. Cargo looks for bench targets in the benches directory next to src.
The function under test
The example measures a recursive Fibonacci function. It is slow on purpose, so the timing is easy to see.
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);Save this as benches/fib_bench.rs. In a real project the function usually lives in your library crate, and the benchmark imports it. Here it sits in the same file to keep the example self-contained.
The parts of a benchmark
The file has four pieces. Each does one job.
- The benchmark function.
bench_fibtakes&mut Criterion. It registers one or more benchmarks. bench_function. It takes a name and a closure. The name identifies the benchmark in the output and in the saved results.Bencher::iter. The closure receives aBencher, calledbhere. Callingb.iter(...)hands Criterion the code to time. Criterion decides how many times to run it.criterion_group!andcriterion_main!. The first collects benchmark functions into a group namedbenches. The second generates themainfunction that runs those groups.
Running it
Run the benchmarks with Cargo:
cargo benchCargo builds the bench target with the optimized bench profile. Criterion then warms up, collects samples, and prints a summary. The exact numbers depend on your machine. The output has this shape:
fib 20 time: [24.1 µs 24.3 µs 24.6 µs]The three values are a lower bound, an estimate, and an upper bound for the time of one call. Later chapters explain how Criterion computes them.
To run only some benchmarks, pass a filter after --. Criterion matches it against benchmark names:
cargo bench -- "fib 20"Flow of a run
Common mistakes
- Forgetting
harness = false. Cargo then links the default test harness too. The build fails with an error about duplicate or missingmain, or the benchmark does not run as expected. - A mismatched bench name. If
nameinCargo.tomldoes not match the file inbenches/, Cargo cannot find the target. - Timing setup inside
iter. Everything inside the closure passed toiteris measured. Build inputs outside it, or useiter_batched, which a later chapter covers. - Running in debug mode. Use
cargo bench, notcargo run. Debug builds are far slower and not representative.
Exercise
You add a file benches/sortbench.rs and a [[bench]] entry with name = "sortbench", but you leave out harness = false. Why is that a problem, and what does criterion_main! provide that the default harness would conflict with?
Show answer
By default, Cargo compiles a bench target with Rust's built-in test harness, which generates its own main function. criterion_main! also generates a main function, so the two conflict and the benchmark does not run correctly. Setting harness = false tells Cargo not to generate the harness, so Criterion's main is the only entry point.
Exercise
In c.benchfunction("fib 20", |b| b.iter(|| fibonacci(blackbox(20)))), which part is timed repeatedly, and what does the string "fib 20" control?
Show answer
The closure passed to b.iter, which is || fibonacci(black_box(20)), is run and timed many times. The string "fib 20" is the benchmark's name. It labels the result in the console and report, it is what a filter such as cargo bench -- "fib 20" matches, and it names the folder where Criterion stores the saved results.