Sub topic 7
Comparing inputs with benchmark groups and BenchmarkId
This chapter assumes you can write a basic bench_function benchmark, that your Cargo.toml already has a [[bench]] target with harness = false, and that you know why black_box is needed. Here you will measure the same code across several inputs, and compare several implementations side by side.
Why a single input is not enough
A benchmark with one input answers only one question: how fast is this code for this size of work? Most real code changes cost as the input grows. A linear scan and a binary search can look similar on ten elements and differ by orders of magnitude on a million.
Running one benchmark per input by hand, with names like "fib 10" and "fib 20", works but has two drawbacks:
- Criterion treats each benchmark as unrelated, so the reports cannot plot them together.
- You have to invent and keep consistent every name yourself.
A benchmark group fixes both. It collects related benchmarks under one name, and Criterion then produces a summary report that compares them.
Benchmark groups
You create a group with Criterion::benchmark_group, add benchmarks to it, and then call finish.
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);There are four pieces to understand:
c.benchmark_group("fibonacci")returns aBenchmarkGroup. The string becomes the first part of every benchmark ID and the name of a directory undertarget/criterion/.group.bench_with_input(id, &input, routine)registers one benchmark. Criterion passes&inputto the closure as its second argument, so the closure receives(b, &n)here.BenchmarkId::from_parameter(n)names the benchmark after the input value. The IDs here arefibonacci/10,fibonacci/15andfibonacci/20.group.finish()consumes the group and writes its summary report. Always call it.
The input is created outside the timed closure. Only the code inside b.iter is measured, so building a large Vec outside it costs nothing in the results.
Choosing a BenchmarkId constructor
A benchmark ID has up to three parts: the group name, an optional function name, and an optional parameter. Which constructor you use decides which parts exist.
| Call | Resulting ID in group `fibonacci` | Use it when |
|---|---|---|
| `BenchmarkId::from_parameter(20)` | `fibonacci/20` | The group holds one function run on several inputs |
| `BenchmarkId::new("recursive", 20)` | `fibonacci/recursive/20` | The group compares several functions on the same inputs |
| `group.bench_function("name", ...)` | `fibonacci/name` | There is no input to vary |
from_parameter and new both require the parameter to implement Display, because Criterion converts it to text for the ID. If your input type is not Display, such as a custom struct, pass a descriptive label as the parameter and hand the real data to bench_with_input separately:
BenchmarkId::new("parse", "small_config")Keep these constraints in mind:
- IDs must be unique within a run. Reusing the same function name and parameter in one group is an error, so add the function name when two benchmarks share an input.
- Avoid
/in function names and labels. The ID is also used to build a directory path, and a slash blurs the group, function and parameter boundaries. - Prefer numeric or short parameters. They sort and plot sensibly.
Comparing two implementations across sizes
The most useful pattern is two or more implementations over the same inputs. This example compares recursive and iterative Fibonacci:
use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion};
fn fib_recursive(n: u64) -> u64 {
match n {
0 | 1 => 1,
n => fib_recursive(n - 1) + fib_recursive(n - 2),
}
}
fn fib_iterative(n: u64) -> u64 {
let (mut a, mut b) = (1u64, 1u64);
for _ in 1..n {
let next = a + b;
a = b;
b = next;
}
b
}
fn bench_fib_compare(c: &mut Criterion) {
let mut group = c.benchmark_group("fib_compare");
for n in [10u64, 20, 25] {
group.bench_with_input(BenchmarkId::new("recursive", n), &n, |b, &n| {
b.iter(|| fib_recursive(black_box(n)))
});
group.bench_with_input(BenchmarkId::new("iterative", n), &n, |b, &n| {
b.iter(|| fib_iterative(black_box(n)))
});
}
group.finish();
}
criterion_group!(benches, bench_fib_compare);
criterion_main!(benches);Both functions return the same value for every n, which you should check before benchmarking. Comparing a fast function that returns the wrong answer against a slow correct one is a common mistake.
The console prints one result block per ID, in the order the loop registers them. For a group like this, expect fib_compare/recursive/10, fib_compare/iterative/10, fib_compare/recursive/20, and so on.
Inputs that are data structures
Parameters are often the size of a data structure rather than a single number. Build each structure once per size, outside the timed closure, and pass it by reference.
use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion};
fn bench_search(c: &mut Criterion) {
let mut group = c.benchmark_group("search");
for size in [1_000usize, 10_000, 100_000] {
let data: Vec<u32> = (0..size as u32).collect();
let target = size as u32 - 1;
group.bench_with_input(BenchmarkId::new("linear", size), &data, |b, data| {
b.iter(|| {
let t = black_box(target);
data.iter().position(|&x| x == t)
})
});
group.bench_with_input(BenchmarkId::new("binary", size), &data, |b, data| {
b.iter(|| data.binary_search(&black_box(target)))
});
}
group.finish();
}
criterion_group!(benches, bench_search);
criterion_main!(benches);The parameter in the ID (size) and the value passed to the closure (&data) are separate. The ID is only a label, and Criterion does not check that it matches the data.
Three details matter in this code:
- The target is the last element, so the linear scan does the maximum amount of work. State which case you are measuring, such as best, worst or average, because the group reports only what you wrote.
black_boxwraps the target, so the compiler cannot treat the search key as a known constant. The wrapper sits outside the per-element comparison, so it does not add cost to every step of the scan.- The data is built with
collectfor each size before registration. Setup that must be repeated for every iteration, such as a mutable copy, needs a different tool, which a later chapter covers.
What the group report shows
After a run, open target/criterion/report/index.html. It links to each group. Each group has its own page, for example target/criterion/search/report/index.html, and each benchmark in it also has a report page.
The group page has two main views:
- A violin plot. It draws one distribution of timings per benchmark ID, which lets you compare functions at each input.
- A line chart. It plots mean time against the parameter for each function, which shows how cost grows with input size. Criterion draws it when the parameters can be placed on an axis, such as numbers.
Read the line chart for shape, not only for values. If one line climbs steeply and another is nearly flat, the two functions have different growth rates, and that is the finding to report.
Running part of a group
Criterion treats the text after -- as a filter on the benchmark ID. It matches as a regular expression, so you can run a slice of a group:
cargo bench -- search/binary
cargo bench -- "fib_compare/.*/20"The first command runs only the binary-search benchmarks. The second runs both Fibonacci implementations at input 20. Filtering saves time while you iterate, but a filtered run produces no complete group summary. Run the whole group before you read the comparison plots.
Group-level settings
A BenchmarkGroup can override settings for its own benchmarks without touching the global configuration:
use criterion::{criterion_group, criterion_main, Criterion};
fn bench_slow(c: &mut Criterion) {
let mut group = c.benchmark_group("slow_group");
group.sample_size(20);
group.bench_function("busy loop", |b| b.iter(|| (0..5_000_000u64).sum::<u64>()));
group.finish();
}
criterion_group!(benches, bench_slow);
criterion_main!(benches);Set the options before you register the benchmarks they should apply to. This is useful when one input is much slower than the others, because you can lower the sample count for that group. Later chapters cover what sample size and measurement time mean statistically.
Common errors
- Timing the setup. Building the input inside
b.itermakes the benchmark measure construction as well as the work. Build it outside, in the group function. - Duplicate IDs. Two
from_parameter(n)calls with the same value in one group collide. UseBenchmarkId::newwith different function names. - Forgetting
finish. Without it the group summary may be missing, so the comparison plots are incomplete. - Comparing across groups. The violin and line plots compare benchmarks within a group only. Put the functions you want compared in the same group.
- Unfair inputs. If two implementations receive different data, the comparison measures the data and not the code. Pass the same reference to both, as the search example does.
- Over-wide input ranges. An input that takes seconds per call makes the whole group slow, because Criterion collects its full set of samples for each ID. Use smaller sizes, or lower the group's sample size.
Exercise
A group named parse runs BenchmarkId::new("fast", len) and BenchmarkId::new("slow", len) for len in [100, 1000]. List the four benchmark IDs, and say what ID you would get if you replaced both calls with BenchmarkId::from_parameter(len).
Show answer
The four IDs are parse/fast/100, parse/slow/100, parse/fast/1000 and parse/slow/1000. With from_parameter(len) for both functions, the IDs would be parse/100 and parse/1000, each used twice. The duplicates collide, so the two functions can no longer be told apart. Keep BenchmarkId::new with distinct function names.
Exercise
In the search benchmark, a colleague moves let data: Vec<u32> = (0..size as u32).collect(); inside the b.iter(...) closure so that "each run starts clean". What happens to the results, and why is the original placement correct for this benchmark?
Show answer
The measured time then includes allocating and filling the vector on every iteration, so both the linear and binary results are dominated by construction and the difference between them shrinks. The original placement builds the vector once per size, outside the timed closure. This is correct because the search does not modify the data, so there is nothing to reset between iterations.