Sub topic 2
Setting up Cargo with a Criterion bench target
This chapter gets a project to the point where cargo bench runs a Criterion benchmark. It covers the dependency, the bench target, the directory layout, and the errors that usually appear on the first try.
It assumes you can read Rust and write closures, and that you know how to run cargo build and cargo test. It also assumes you have edited Cargo.toml before and know what a dev-dependency is. The benchmark itself is minimal here. Later chapters explain how to write good ones.
Why Criterion needs its own target
Rust has a built-in #[bench] attribute, but it works only on nightly. The built-in harness is the test runner, called libtest. It provides the main function and collects #[test] and #[bench] items.
Criterion works on stable Rust. It supplies its own main, so it must replace libtest. You do that with the harness = false setting on a bench target.
Cargo handles benchmarks in three steps:
- Cargo finds bench targets. By default, every
.rsfile inbenches/is one. - Cargo compiles each target in the
benchprofile, which inherits fromrelease. - Cargo runs each resulting binary.
If the harness is not disabled, libtest generates a main and Criterion's main is never used.
Creating the project
Create a library crate. The name fib_demo is used throughout this chapter.
cargo new fib_demo --lib
cd fib_demo
mkdir benchesThe layout you are aiming for:
fib_demo/
├── Cargo.toml
├── src/
│ └── lib.rs
└── benches/
└── fib_bench.rsWhy a library crate
Files in benches/ are separate crates. Like integration tests in tests/, they can import only your package's public library API. A binary-only crate (just src/main.rs) exposes nothing to import. If your code is a binary, move the logic you want to measure into src/lib.rs and have main.rs call it.
Put the function under test in src/lib.rs:
/// Naive recursive Fibonacci, used as a stand-in workload.
pub fn fibonacci(n: u64) -> u64 {
match n {
0 | 1 => 1,
n => fibonacci(n - 1) + fibonacci(n - 2),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn small_values() {
assert_eq!(fibonacci(0), 1);
assert_eq!(fibonacci(5), 8);
}
}The function has to be pub. A private function in the library cannot be imported from a bench file.
Editing Cargo.toml
Here is the complete manifest:
[package]
name = "fib_demo"
version = "0.1.0"
edition = "2021"
[dependencies]
[dev-dependencies]
criterion = { version = "0.5", features = ["html_reports"] }
[[bench]]
name = "fib_bench"
harness = falseEach part has a purpose.
The dev-dependency
Criterion goes under [dev-dependencies], not [dependencies]. Dev-dependencies are compiled for tests, examples, and benchmarks. They are not part of your library when other crates depend on it. Users of your crate never download or build Criterion.
The html_reports feature turns on the HTML report with per-benchmark pages and plots. The report is generated by Criterion itself. It does not require a plotting tool. Criterion can optionally use gnuplot for plots, and it falls back to its own plotting backend if gnuplot is missing. Leave the feature out to build faster and write less to disk, but you will lose the report pages.
The bench target
[[bench]] is a TOML array of tables. Each entry declares one bench target. Two fields matter:
namemust match the file name without the extension.name = "fib_bench"points tobenches/fib_bench.rs.harness = falsestops Cargo from linking libtest and lets Criterion'smainbe the entry point.
A second benchmark file needs its own [[bench]] entry with harness = false:
[[bench]]
name = "fib_bench"
harness = false
[[bench]]
name = "sort_bench"
harness = falseIf you leave out the entry, Cargo still discovers the file under benches/, but with the default harness. That is the cause of most first-run failures, covered below.
The first bench file
Create benches/fib_bench.rs:
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use fib_demo::fibonacci;
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 structure has three parts:
bench_fibtakes a&mut Criterion. It registers one benchmark named"fib 20".criterion_group!(benches, bench_fib)bundles benchmark functions into a group calledbenches.criterion_main!(benches)expands to amainfunction that runs that group.
black_box stops the compiler from precomputing fibonacci(20). The next chapters explain it and the measurement loop. For now, treat this as the template.
Running it
cargo benchThe first run compiles Criterion and its dependencies, which takes a while. Later runs rebuild only your code. You will see output like this, with numbers that depend on your machine:
fib 20 time: [21.5 µs 21.6 µs 21.8 µs]Criterion also writes files under target/criterion/. The HTML report is at target/criterion/report/index.html.
The diagram shows what happens after you run the command:
Selecting what to run
With several benchmarks, you rarely want to run all of them.
# Run only one bench target (file)
cargo bench --bench fib_bench
# Run benchmarks whose name contains "fib 20"
cargo bench -- "fib 20"
# Combine both
cargo bench --bench fib_bench -- "fib 20"Arguments before -- go to Cargo. Arguments after -- go to the benchmark binary, where Criterion reads them. The filter is a regular expression matched against the benchmark name.
Setup errors and their fixes
Forgetting harness = false
If the [[bench]] entry is missing or lacks harness = false, libtest supplies main, and Criterion's main is never called. The usual symptom is that cargo bench finishes with running 0 tests and no Criterion output. Add the entry, or set harness = false, and rerun.
Unrecognized option: 'save-baseline'
cargo bench -- --save-baseline before sends the flag to every bench binary Cargo builds. That includes the unit tests in your library, which still use libtest. libtest does not know Criterion's flags and fails with an error like Unrecognized option: 'save-baseline'.
There are two fixes. The first is to name the target:
cargo bench --bench fib_bench -- --save-baseline beforeThe second is to stop Cargo from building the library as a bench target by adding this to Cargo.toml:
[lib]
bench = falseIf you also have a binary target, add [[bin]] with bench = false for the same reason. This matters whenever you pass Criterion-specific flags, such as baselines, which a later chapter covers.
unresolved import fib_demo
The bench file imports from the package's library, so the crate name in the use line must match [package] name with hyphens replaced by underscores. A package named fib-demo is imported as fib_demo. If the package has no src/lib.rs, there is nothing to import.
Benchmarking a debug build
cargo bench uses the bench profile, which is optimized. cargo run and cargo test use the unoptimized dev profile, and numbers measured there are meaningless for performance work. If you need to change optimization settings for benchmarks, edit the profile:
[profile.bench]
debug = trueThis keeps optimizations but adds debug symbols. Profilers such as perf need symbols to show readable function names.
Checking that benchmarks still compile
Benchmark code rots like any other code if it is never built. cargo test --benches builds the bench targets and runs them in a quick test mode. Criterion runs each benchmark function once, with no timing analysis, to confirm that it does not panic.
cargo test --benchescargo test --all-targets includes benchmarks along with unit tests, integration tests, and examples. This is a cheap check for continuous integration, and it is much faster than a full benchmark run.
Summary of the setup
| Item | Where | Purpose |
|---|---|---|
| `criterion` | `[dev-dependencies]` | Benchmarking library, not shipped to users |
| `html_reports` feature | Criterion dependency | Writes HTML reports under `target/criterion` |
| `[[bench]] name` | `Cargo.toml` | Must match the file in `benches/` |
| `harness = false` | `[[bench]]` | Lets Criterion provide `main` |
| `src/lib.rs` | Package | Exposes public functions to the bench crate |
| `bench = false` | `[lib]` | Keeps libtest from receiving Criterion flags |
Exercise
You add benches/parsebench.rs with a correct criterionmain!, but you forget to add a [[bench]] entry. What does cargo bench --bench parse_bench show, and what single change fixes it?
Show answer
Cargo discovers the file automatically but builds it with the default libtest harness. libtest generates its own main, so Criterion's main never runs, and the output shows "running 0 tests" with no Criterion results. Add [[bench]] with name = "parse_bench" and harness = false to Cargo.toml.
Exercise
A teammate runs cargo bench -- --save-baseline main in a package that has a library and a Criterion bench target. The command fails with "Unrecognized option: 'save-baseline'". Why does it fail, and what are two ways to avoid it?
Show answer
The flag after -- is passed to every bench binary, including the library's unit-test binary, which uses libtest and does not know the flag. Either name the Criterion target with cargo bench --bench fib_bench -- --save-baseline main, or set bench = false under [lib] in Cargo.toml so the library is not built as a bench target.