Sub topic 8
Keeping setup out of the measurement with iter_batched
This chapter assumes you have a working Criterion bench target (harness = false), and that you can write a benchmark with bench_function and Bencher::iter. It also assumes you know black_box. You should be comfortable with closures that take ownership of values (FnMut() -> T, move semantics).
The problem: setup that leaks into the timing
Bencher::iter times the entire closure you give it. That is fine when the closure only calls a pure function on fixed input. It breaks down when the code under test consumes or mutates its input.
Take an in-place sort. After the first call the vector is sorted, and every later call sorts already sorted data. You are no longer measuring what you meant to measure. The obvious fix is to build a fresh input inside the closure:
use criterion::{black_box, criterion_group, criterion_main, Criterion};
fn bench_sort_naive(c: &mut Criterion) {
let data: Vec<u32> = (0..1000).rev().collect();
c.bench_function("sort 1000 reversed (clone inside iter)", |b| {
b.iter(|| {
let mut v = data.clone(); // allocation and copy are timed
v.sort();
black_box(v)
})
});
}
criterion_group!(benches, bench_sort_naive);
criterion_main!(benches);This now sorts unsorted data each time, but the clone is part of the measurement. The reported time is "clone plus sort". If the clone costs 300 ns and the sort costs 2 µs, you have inflated the result by about 15%. You also cannot tell which part changed when the number moves later.
iter_batched fixes this. You pass a setup closure and a routine closure, and Criterion times only the routine.
How iter_batched works
The signature, simplified, is:
fn iter_batched<I, O, S, R>(&mut self, setup: S, routine: R, size: BatchSize)
where
S: FnMut() -> I,
R: FnMut(I) -> O,setupproduces one input of typeI. It is never timed.routinetakes that input by value and returns an output of typeO. It is timed.sizetells Criterion how many inputs to prepare before each timed stretch.
For each sample, Criterion needs to run the routine a certain number of times (the iteration count it chose during warm-up). It splits those iterations into batches. For each batch it:
- Calls
setuponce per iteration in the batch and stores the inputs in aVec. - Starts the timer.
- Feeds each input to
routineand collects the outputs in anotherVec. - Stops the timer.
- Drops the outputs, outside the timed region.
Two consequences follow from this design:
- The routine receives ownership of the input, so it can consume or mutate it freely.
- The cost of dropping the output is not measured. If freeing memory is part of what you want to measure, see the section on drop costs below.
A first example with iter_batched
This is the sort benchmark rewritten so that cloning is excluded:
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() borrows data from the enclosing function. Criterion calls it as often as it needs. The routine takes mut v by value, sorts it, and returns it through black_box. Returning the vector also matters for correctness: the optimizer cannot prove that the sort result is unused, so it cannot delete the sort.
Run it and compare with the naive version. The iter_batched number should be lower, by roughly the cost of a 4 KB clone.
Choosing a BatchSize
BatchSize controls how many inputs Criterion creates before each timed stretch. A larger batch means fewer timer calls but more inputs alive in memory at once.
| Variant | Behavior | Use when |
|---|---|---|
| `SmallInput` | Few, large batches (about ten per sample). Many inputs exist at the same time. | Inputs are small enough that thousands fit comfortably in memory or cache. |
| `LargeInput` | Many, smaller batches (up to about a thousand per sample). Fewer inputs alive at once. | Inputs are big enough that holding many of them would pressure memory. |
| `PerIteration` | One input per timed call, with the timer started and stopped around each call. | Only one input can exist at a time, or inputs must not be created ahead of time. |
| `NumBatches(n)` | Exactly `n` batches per sample. | You need to control the batch count directly. |
| `NumIterations(n)` | Exactly `n` iterations per batch. | You need to control the batch length directly. |
Pick SmallInput by default, and move to LargeInput if memory use becomes a problem. Use PerIteration only when you have to. The timer has its own cost, so with a very short routine that cost becomes a noticeable share of the measurement. It is also harder to compare numbers across batch sizes, because batching changes cache behavior: many freshly cloned vectors laid out in memory are not the same workload as one vector that is cloned and sorted immediately.
Borrowing the input with iter_batched_ref
Sometimes the routine should not own the input. The common case is a large buffer that you want to mutate, where the cost of dropping it would otherwise be mixed into your analysis. iter_batched_ref passes &mut I to the routine instead of I. The input is dropped by Criterion after the timer stops.
use criterion::{black_box, criterion_group, criterion_main, BatchSize, Criterion};
fn bench_sort_ref(c: &mut Criterion) {
let data: Vec<u32> = (0..1000).rev().collect();
c.bench_function("sort_unstable 1000 reversed", |b| {
b.iter_batched_ref(
|| data.clone(),
|v| {
v.sort_unstable();
black_box(v.len())
},
BatchSize::SmallInput,
)
});
}
criterion_group!(benches, bench_sort_ref);
criterion_main!(benches);Here the routine gets v: &mut Vec<u32>. It returns a small value (v.len()) through black_box. That is enough to keep the call alive. The side effect on v is observable through the reference, so the sort itself cannot be removed.
Use iter_batched when the routine naturally consumes its input (for example, into_iter() or a function that takes a Vec by value). Use iter_batched_ref when the routine naturally takes &mut.
Drop costs and the output
Outputs returned from the routine are collected and dropped after the timer stops. This is usually what you want, but not always.
- If you are benchmarking something where deallocation is a real part of the cost (a custom allocator, a data structure with a heavy
Drop), the omission hides that cost. Benchmark it with plainiterand build the value inside the closure, or measure the drop in its own benchmark. - If you want to measure a routine whose result is large and should not count its drop, returning the result from the routine is the correct approach.
Bencher::iter_with_large_dropexists for the same purpose withiter.
Comparing batch sizes in one run
You can check how much the batch size affects your own workload by putting variants in one group. This example uses a larger vector, so the memory difference between SmallInput and LargeInput is visible.
use criterion::{black_box, criterion_group, criterion_main, BatchSize, Criterion};
fn bench_sort_batch_sizes(c: &mut Criterion) {
let data: Vec<u64> = (0..100_000).rev().collect();
let mut group = c.benchmark_group("sort 100k reversed");
group.bench_function("SmallInput", |b| {
b.iter_batched(
|| data.clone(),
|mut v| {
v.sort();
black_box(v)
},
BatchSize::SmallInput,
)
});
group.bench_function("LargeInput", |b| {
b.iter_batched(
|| data.clone(),
|mut v| {
v.sort();
black_box(v)
},
BatchSize::LargeInput,
)
});
group.bench_function("PerIteration", |b| {
b.iter_batched(
|| data.clone(),
|mut v| {
v.sort();
black_box(v)
},
BatchSize::PerIteration,
)
});
group.finish();
}
criterion_group!(benches, bench_sort_batch_sizes);
criterion_main!(benches);Each input is 800 KB, so SmallInput may keep many megabytes alive at once. Results will differ by machine. If all three agree within the reported confidence intervals, the batch size does not matter for this routine, and you can keep the simplest choice. If they disagree, the routine is sensitive to memory layout or timer overhead, and you should report which setting you used.
Common mistakes
- Doing setup inside the routine. If the routine closure calls
clone()or builds a fixture, it is timed again. Everything in the second closure is measured. - Forgetting the output. A routine that ends with
;and returns()gives the optimizer room to remove work. Return the result, or wrap it inblack_box. - Using
PerIterationout of habit. It is correct, but it adds timer overhead to every call. - Setup that is not deterministic. If setup generates random data, seed the generator. Otherwise, run-to-run differences come from the input, not the code, and Criterion may report a change that is only a different random draw.
- Sharing mutable state between iterations. Each call to
setupshould return an independent input. If setup returns clones of one shared structure that the routine mutates through interior mutability, later iterations see earlier changes.
Exercise
You benchmark a function dedup_in_place(v: &mut Vec<u32>) on a vector with many duplicates. Using plain b.iter(|| dedup_in_place(&mut data)) gives a suspiciously fast result. Why, and which Criterion method and BatchSize would you use to fix it?
Show answer
After the first call, data has no duplicates left, so every later call works on already deduplicated data and does almost nothing. Use iter_batched_ref with a setup closure that clones the original vector, a routine closure that takes &mut Vec<u32> and calls dedup_in_place, and BatchSize::SmallInput (or LargeInput if the vectors are big). Return something small through black_box, such as v.len(), so the call is kept.
Exercise
A routine takes about 40 ns per call. Why is BatchSize::PerIteration a poor choice for it, and what would you use instead?
Show answer
With PerIteration, the timer is started and stopped around each call. The timer overhead is a large share of 40 ns, so it distorts the result. Use SmallInput, which runs many calls inside one timed stretch and amortizes the timer cost.