Sub topic 7
Comparing inputs with benchmark groups and BenchmarkId
This chapter assumes you can already write a single benchmark with bench_function and black_box, and that your project has a [[bench]] target with harness = false. Here you will measure one function across several input sizes and read the results side by side.
Why one benchmark is not enough
A single timing tells you how fast a function is for one input. It does not tell you how the cost grows. The recursive Fibonacci function below does roughly 1.6 times more work for each step in n. You can only see that by measuring several values of n in the same run.
You could write three separate bench_function calls named "fib 10", "fib 15" and "fib 20". That works, but the reports are unrelated to each other. A benchmark group solves this by putting the related measurements under one name.
Benchmark groups
A benchmark group is a named collection of benchmarks that Criterion reports together. You create one with Criterion::benchmark_group, add benchmarks to it, and then call finish.
Each benchmark in a group is identified by the group name plus a function or parameter name. For example, fibonacci/10 is the benchmark for input 10 in the group fibonacci. Criterion also uses these names for the directories under target/criterion and for the HTML report.
BenchmarkId and bench_with_input
BenchmarkId is the label for one benchmark inside a group. BenchmarkId::from_parameter(n) builds a label from the input value alone. BenchmarkId::new("name", n) builds a label from a function name and a parameter, which is useful when you compare several implementations.
bench_with_input takes the label, a reference to the input, and a closure. The closure receives the Bencher and the input reference.
use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion};
fn fibonacci(n: u64) -> u64 {
match n {
0 | 1 => 1,
n => fibonacci(n - 1) + fibonacci(n - 2),
}
}
fn bench_fib_inputs(c: &mut Criterion) {
let mut group = c.benchmark_group("fibonacci");
for n in [10u64, 15, 20] {
group.bench_with_input(BenchmarkId::from_parameter(n), &n, |b, &n| {
b.iter(|| fibonacci(black_box(n)))
});
}
group.finish();
}
criterion_group!(benches, bench_fib_inputs);
criterion_main!(benches);Three details matter here:
- The pattern
|b, &n|destructures the reference, soninside the closure is a plainu64. black_box(n)is still needed inside the timed closure. Passing the input throughbench_with_inputdoes not hide it from the optimizer.group.finish()ends the group. Skipping it can leave the group's summary unwritten.
Run it with cargo bench. The console prints one result per input, named fibonacci/10, fibonacci/15 and fibonacci/20.
Reading the group report
Open target/criterion/report/index.html after the run. Each input has its own page, with the timing distribution and the same statistics as a single benchmark. The group also gets a summary page.
For numeric parameters, the summary draws a line plot of time against the parameter value. This is where growth shows up. If time doubles whenever the input doubles, the cost is roughly linear. If it grows much faster, you are looking at something closer to quadratic or exponential behavior, as with this Fibonacci function.
Choosing good inputs
Pick inputs that cover the range you care about in production, not just convenient values.
- Include a small, a typical and a large size. A function can be fast for small inputs and slow for large ones because of cache effects.
- Keep the number of inputs modest. Each one is measured for the full measurement time, so ten inputs take ten times as long as one.
- Build large inputs once, outside the loop passed to
iter, and borrow them. Constructing data inside the timed closure measures the construction as well.
Common mistakes
- Forgetting
group.finish(). - Using
bench_functioninside a loop with the same name, which makes every iteration overwrite the previous results. Use a uniqueBenchmarkIdper input. - Applying
black_boxto the result but not the input, which lets the compiler fold a constant input into a precomputed answer.
Exercise
You want to compare two sorting implementations, sort_a and sort_b, on inputs of 100, 1000 and 10000 elements, all in one group. How would you label each benchmark so the report shows both implementations for each size?
Show answer
Create one group, for example c.benchmark_group("sort"). Loop over the sizes and, for each size, call bench_with_input twice, once with BenchmarkId::new("sort_a", size) and once with BenchmarkId::new("sort_b", size). The function name distinguishes the implementation and the parameter distinguishes the size, so the report can plot both lines on one chart. Call group.finish() at the end.