Sub topic 3
Writing your first benchmark
This chapter turns the project setup into a working benchmark. You will write one, run it, and learn what each line of the file does. It assumes you can write Rust functions and closures, run cargo build and cargo test, and edit Cargo.toml. Reading the timing report and the statistics behind it come in later chapters.
The project layout
Criterion benchmarks live in the benches/ directory, next to src/ and tests/. Each file in benches/ is a separate benchmark target. Cargo only treats it as a Criterion benchmark if you declare it in Cargo.toml.
Here is a complete manifest for a small library crate called fibdemo:
[package]
name = "fibdemo"
version = "0.1.0"
edition = "2021"
[dev-dependencies]
criterion = { version = "0.5", features = ["html_reports"] }
[[bench]]
name = "fib_bench"
harness = falseThe name in [[bench]] must match the file name benches/fib_bench.rs, without the extension. harness = false turns off Rust's built-in test harness for this target. The built-in harness supplies its own main function. Criterion supplies a different main through the criterion_main! macro, so the two cannot coexist.
The directory tree looks like this:
fibdemo/
├── Cargo.toml
├── src/
│ └── lib.rs
└── benches/
└── fib_bench.rsBenchmark the library, not a binary
A benchmark file is a separate crate. It can only use the public API of your library, the same way an integration test does. It cannot import functions from src/main.rs. If your code is in a binary crate, move the logic into src/lib.rs and call it from main.rs.
Put the function under test in src/lib.rs:
pub fn fibonacci(n: u64) -> u64 {
match n {
0 | 1 => 1,
n => fibonacci(n - 1) + fibonacci(n - 2),
}
}This recursive version is deliberately slow. It does an amount of work that is easy to measure, which makes it a good first target.
The first benchmark file
Create benches/fib_bench.rs:
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use fibdemo::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 file has four parts.
- The imports.
Criterionis the object that runs and records benchmarks.black_boxis covered in the next chapter. For now, read it as "hide this value from the optimizer". - The benchmark function.
bench_fibtakes&mut Criterion. The name is arbitrary, but the signature must match exactly. criterion_group!. This macro creates a function namedbenchesthat runs every listed benchmark function in order. You can list several:criterion_group!(benches, bench_a, bench_b);.criterion_main!. This macro generates themainfunction. It runs each group you pass to it.
What the closures do
c.bench_function("fib 20", ...) registers one benchmark. The first argument is its ID. Criterion uses the ID as the display name, as the directory name for saved results, and as the filter key on the command line. The second argument is a closure that receives a &mut Bencher.
The Bencher has one method you will use most: iter. You give it a closure containing the code to time:
b.iter(|| fibonacci(black_box(20)))Criterion calls the inner closure many times in a loop and measures the total. The loop count is chosen automatically, so you never write a for loop yourself. Anything outside the b.iter(...) call is not timed. The outer closure runs once, so it is the place for one-time setup, such as building a large input.
This shows the split:
use criterion::{black_box, criterion_group, criterion_main, Criterion};
fn bench_sum_of_squares(c: &mut Criterion) {
// Runs once. Not measured.
let data: Vec<u64> = (1..=1_000).collect();
c.bench_function("sum of squares 1000", |b| {
// Runs many times. Measured.
b.iter(|| data.iter().map(|x| x * x).sum::<u64>())
});
}
criterion_group!(benches, bench_sum_of_squares);
criterion_main!(benches);The vector is built once and reused, so the report reflects the iterator pipeline and not the allocation. If each iteration needs a fresh copy of the data, a different method is the right tool. That method is iter_batched, which has its own chapter.
The return value matters
The closure passed to iter should return the result of the work, as both examples above do. Criterion passes the returned value through its own black box. That gives you some protection against the compiler deleting a computation whose result is never used. A closure that ends in a semicolon returns () and loses that protection:
// Risky: the result is dropped inside the closure.
b.iter(|| { fibonacci(20); });
// Better: the result is returned to Criterion.
b.iter(|| fibonacci(20));Wrapping the input in black_box is still worthwhile. Without it, the compiler can see that 20 is a constant and may compute the whole answer at compile time.
Running it
Run all benchmarks with:
cargo benchCargo builds the bench profile, which is optimized like --release. That is the point of benchmarking: debug builds can be 10 to 100 times slower and have a different performance profile. Cargo then runs each benchmark target.
You can pass a filter after --. Criterion treats it as a substring or regular expression matched against benchmark IDs:
cargo bench -- "fib 20"
cargo bench --bench fib_benchThe first command runs only benchmarks whose ID matches fib 20. The second runs only the fib_bench target and skips any other files in benches/.
Criterion prints a few lines per benchmark. For this one you will see something like the following. Your numbers will differ with the CPU and the load on the machine:
fib 20 time: [17.8 µs 17.9 µs 18.0 µs]The three values are a lower bound, a best estimate, and an upper bound for the time of one call. Reading these lines and the HTML report is the subject of a later chapter. If you ran the benchmark before, Criterion also compares the new result against the previous run and reports whether performance changed.
What happens during a run
The next chapters go into the statistics. Here is the sequence of events for one bench_function call.
During warm-up, Criterion calls your closure repeatedly for a short period so that caches and CPU clock speeds settle. During measurement, it collects a fixed number of samples, and each sample times a batch of iterations. Results are written under target/criterion/, in a directory named after the benchmark ID. That directory is where later runs find the previous result to compare against.
Common errors
These are the problems most people hit on the first attempt.
- The benchmark runs but prints "running 0 tests" and no timings. The
[[bench]]entry is missingharness = false, or itsnamedoes not match the file name. Cargo is running the built-in harness instead of Criterion. unresolved import fibdemo. The package has nosrc/lib.rs, or the function is notpub. The crate name in theuseline is the package name with hyphens replaced by underscores.- A benchmark finishes instantly and reports a few picoseconds. The compiler removed the work. Pass inputs through
black_boxand return the result from the closure. - Numbers vary widely between runs. Close other programs and avoid laptop battery mode. Noise is a later chapter, but a quiet machine already helps.
- Slow numbers that never improve. You may be running with
cargo runorcargo testinstead ofcargo bench. Onlycargo benchuses the optimized benchmark profile.
Putting it together
A good first workflow looks like this:
- Put the code you want to measure in
src/lib.rsand make itpub. - Add the
criteriondev-dependency and a[[bench]]entry withharness = false. - Write a function that takes
&mut Criterionand callsbench_function. - Time only the work inside
b.iter(|| ...), with inputs wrapped inblack_boxand the result returned. - Register the function with
criterion_group!and finish the file withcriterion_main!. - Run
cargo benchand confirm that the benchmark prints a plausible time.
Once this runs, adding more benchmarks means writing more functions and listing them in the group.
Exercise
You add benches/parse_bench.rs and write a correct Criterion benchmark, but cargo bench prints "running 0 tests" and no timings. Your Cargo.toml contains [[bench]] with name = "parse_bench". What is the most likely missing line, and why does it fix the problem?
Show answer
The [[bench]] entry is missing harness = false. Without it, Cargo builds the file with Rust's built-in test harness, which supplies its own main and ignores the main generated by criterion_main!, so Criterion never runs. Setting harness = false disables the built-in harness and lets Criterion's main run the benchmarks.
Exercise
In this benchmark, which parts are timed and which are not? fn bench(c: &mut Criterion) { let text = "a,b,c".repeat(1000); c.bench_function("split", |b| b.iter(|| text.split(',').count())); }
Show answer
Only the closure passed to b.iter, which calls text.split(',').count(), is timed. Building text with repeat happens once in the outer function and is not measured. The count is returned from the closure, so Criterion receives the result.