Sub topic 2
Setting up Cargo with a Criterion bench target
This chapter assumes you can build and test a Rust project with Cargo, edit Cargo.toml, and know what a dev-dependency is. By the end you will have a project with a Criterion benchmark target that compiles and runs.
Why benchmarks need their own target
Cargo treats files in the benches/ directory as separate benchmark targets. Each file is compiled as its own executable, apart from your library code. A benchmark file can only use the public API of your crate, the same as an integration test in tests/.
Rust has a built-in benchmark harness, but it works only on the nightly compiler. Criterion works on stable Rust. To use it, you tell Cargo not to use the built-in harness.
Create the project
Start with a library crate so the benchmark has something to import:
cargo new fib_demo --lib
cd fib_demo
mkdir benchesThe layout will look like this:
fib_demo/
├── Cargo.toml
├── src/
│ └── lib.rs
└── benches/
└── fib_bench.rsEdit Cargo.toml
Add Criterion as a dev-dependency and declare the bench target:
[dev-dependencies]
criterion = { version = "0.5", features = ["html_reports"] }
[[bench]]
name = "fib_bench"
harness = falseEach part has a job:
[dev-dependencies]makes Criterion available to benchmarks, tests, and examples. It is not compiled into your library for users of your crate.- The
html_reportsfeature produces the HTML report you will read in a later chapter. It needs no extra setup. [[bench]]with double brackets declares one benchmark target. The brackets mean the table can appear more than once, once per benchmark file.namemust match the file name inbenches/, without the.rsextension. Here that isbenches/fib_bench.rs.harness = falseturns off the default test harness for this target.
The last setting matters most. The default harness supplies a main function that runs #[bench] functions. Criterion needs to supply its own main, and two main functions would conflict. With harness = false, Cargo leaves main to Criterion.
The skeleton of a benchmark file
Every Criterion benchmark file has the same three parts: benchmark functions, a group, and a main. Here is the complete file for 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);The next chapter walks through this code line by line. For now, note how the pieces connect:
bench_fibtakes a&mut Criterionand registers a benchmark.criterion_group!collects benchmark functions into a named group, herebenches.criterion_main!generates themainfunction that runs the groups you list.
Run it
From the project root, run:
cargo benchCargo compiles the benchmark in release mode, using the bench profile, which inherits from release. This is the right setting, because timings from unoptimized debug builds say little about real performance. The first run takes a while because Criterion and its dependencies must compile. Later runs reuse the build.
You can run one target by name:
cargo bench --bench fib_benchYou can also pass a filter after --. Criterion runs only benchmarks whose names contain the text:
cargo bench -- "fib 20"Common setup errors
| Symptom | Likely cause |
|---|---|
| "running 0 tests" and no timings | `harness = false` is missing from the `[[bench]]` entry |
| "can't find `fib_bench` bench" | `name` in `Cargo.toml` does not match the file name in `benches/` |
| "unresolved import `criterion`" | Criterion is under `[dependencies]` typos, or missing from `[dev-dependencies]` |
| "unresolved import `fib_demo`" | The code you benchmark is not `pub`, or the crate has no `lib.rs` |
Exercise
A teammate adds benches/sort_bench.rs that uses Criterion, but cargo bench prints "running 0 tests". The file compiles without errors. What do you check in Cargo.toml, and what must the entry look like?
Show answer
Check for a [[bench]] entry for the file. It must read [[bench]], name = "sort_bench", and harness = false. Without harness = false, Cargo uses the default harness, which finds no #[bench] functions and so reports zero tests. The name must match the file name without .rs.