Sub topic 8
Keeping setup out of the measurement with iter_batched
This chapter assumes you can write a basic Criterion benchmark with bench_function and Bencher::iter, and that your project already has the harness = false bench target from earlier chapters.
The problem: setup inside the timed closure
Bencher::iter times everything inside its closure. Suppose you want to benchmark Vec::sort. Sorting mutates its input, so each iteration needs a fresh unsorted vector. If you clone the vector inside iter, the clone is timed along with the sort:
b.iter(|| {
let mut v = data.clone(); // timed, but not what you want to measure
v.sort();
v
})The result is the cost of cloning plus sorting. For a cheap operation, the clone can dominate the number.
If you sort the same vector repeatedly, the problem reverses. After the first iteration the data is already sorted, so you measure the sort of sorted input, which is a different case.
How iter_batched works
Bencher::iter_batched takes three arguments:
- A setup closure that produces the input. It is not timed.
- A routine closure that takes the input by value. Only this closure is timed.
- A
BatchSizethat tells Criterion how many inputs to prepare before each timed run.
Criterion builds a batch of inputs, starts the clock, runs the routine on each input, and stops the clock. Setup cost never enters the measurement.
use criterion::{black_box, criterion_group, criterion_main, BatchSize, Criterion};
fn bench_sort(c: &mut Criterion) {
let data: Vec<u32> = (0..1000).rev().collect();
c.bench_function("sort 1000 reversed", |b| {
b.iter_batched(
|| data.clone(),
|mut v| {
v.sort();
black_box(v)
},
BatchSize::SmallInput,
)
});
}
criterion_group!(benches, bench_sort);
criterion_main!(benches);The setup closure || data.clone() runs outside the timer. The routine receives the clone as v, sorts it, and returns it through black_box. Returning the value also means its drop happens after the timer stops in Criterion's batch loop, so deallocation is not counted in the routine either.
Choosing a BatchSize
BatchSize controls how many inputs Criterion holds in memory at once. This is a trade-off between timer overhead and memory use.
| Variant | Use it when |
|---|---|
| `SmallInput` | Inputs are small, so many can sit in memory together. This gives the least timing overhead. |
| `LargeInput` | Inputs are large enough that holding many would use too much memory. Batches are smaller. |
| `PerIteration` | Each input must be prepared right before its own run. Timer overhead is highest, so use it only when needed. |
For the 1000-element vector above, SmallInput is appropriate. If each input were hundreds of megabytes, LargeInput or PerIteration would avoid exhausting memory.
iter_batched or iter_batched_ref
If the routine does not need to own its input, use iter_batched_ref. It passes &mut to the input, and the input is dropped outside the timed section. That avoids both the clone-in-routine mistake and the cost of dropping a large value inside the timer. Use iter_batched when the routine consumes the value, as Vec::into_iter or a function taking ownership would.
Checking your benchmark
Run it the same way as any other benchmark:
cargo benchCompare the result with a version that clones inside iter. The batched version should report a lower time, and the gap tells you how much the clone was costing.
Common mistakes
- Using
iterwith a clone inside it, which times the clone. - Forgetting
black_boxon the routine's result, which lets the compiler discard the work. - Choosing
PerIterationby default and measuring timer overhead instead of the routine. - Benchmarking a mutating function on one shared input, so later iterations see already-modified data.
Exercise
You benchmark a function that takes a String by value and returns its length after trimming. Each call needs a fresh string built with " hello ".repeat(1000). Which Criterion method and BatchSize do you pick, and where does the repeat call go?
Show answer
Use b.iter_batched with BatchSize::SmallInput. Put the repeat call in the setup closure, for example || " hello ".repeat(1000), so it is not timed. The routine closure takes the String, trims it, and returns the length through black_box. The string is about 9 KB, which is small, so SmallInput is appropriate.