Sub topic 4
Keeping the compiler honest with black_box
This chapter assumes you can write a basic Criterion benchmark with bench_function and Bencher::iter, and that you know cargo bench builds with optimizations. You do not need to read assembly. Where assembly matters, the chapter says how to look at it.
Why a benchmark can lie
Criterion times a closure. It cannot see what the closure computes, and neither can you from the timings alone. The Rust compiler (through LLVM) sees the whole closure and every function it calls. If it can prove that the result is the same on every run, it may compute the result at compile time. If it can prove that the result is never used, it may delete the work.
A benchmark that the optimizer has gutted still compiles and runs. It reports a very fast time, often well under a nanosecond, and nothing warns you.
Three optimizations cause most of these cases:
- Constant folding: the compiler evaluates an expression whose inputs are all known at compile time and replaces it with the answer.
- Dead code elimination: the compiler removes computations whose results are never observed.
- Loop-invariant code motion: the compiler moves a computation that gives the same result on every iteration out of the loop. The timed loop then repeats almost nothing.
All three are correct for normal programs, and they are why release builds are fast. In a benchmark they hide the work you wanted to measure.
A benchmark that measures nothing
Here is a function with a literal argument. The compiler knows the argument and the whole body.
use criterion::{black_box, criterion_group, criterion_main, Criterion};
fn square_sum(n: u64) -> u64 {
(1..=n).map(|x| x * x).sum()
}
fn bench_naive(c: &mut Criterion) {
c.bench_function("square_sum naive", |b| b.iter(|| square_sum(1000)));
}
fn bench_honest(c: &mut Criterion) {
c.bench_function("square_sum black_box", |b| {
b.iter(|| square_sum(black_box(1000)))
});
}
criterion_group!(benches, bench_naive, bench_honest);
criterion_main!(benches);Put this in benches/square_bench.rs and register it with harness = false as in the setup chapter. On most toolchains the first benchmark reports a time around a nanosecond or less. A loop of 1000 multiplications cannot run that fast. The compiler has turned the loop into a closed-form formula or a constant. The second benchmark reports a much larger time, because the compiler can no longer assume n is 1000.
Exact numbers depend on your compiler version and CPU. The compiler may not fold this particular loop on your toolchain, so you may see no gap between the two. That does not make the naive version safe. It only means this optimizer did not catch it this time. A compiler upgrade could change the result without any change to your code.
What black_box does
black_box takes a value and returns it unchanged. The compiler is told to treat the call as opaque. It must assume the function could do anything with the value, and that the returned value could be anything. It therefore cannot reason about the value's contents before or after the call.
use criterion::black_box;
fn main() {
let n = black_box(1000u64);
println!("{}", n);
}At runtime this costs almost nothing. The value is stored somewhere the optimizer cannot see through, then read back.
Criterion's black_box lives in the criterion crate. Since Rust 1.66 there is also std::hint::black_box. Both do the same job in a benchmark. Newer Criterion releases point their own black_box at the standard library one, and use std::hint::black_box; is the more future-proof import. Pick one per project and use it consistently.
Two places to apply it
Apply black_box in two places: on inputs and on outputs.
Inputs
Wrap any input the compiler could otherwise know at compile time. This blocks constant folding and loop-invariant hoisting.
use criterion::{black_box, criterion_group, criterion_main, Criterion};
fn sum_slice(values: &[u64]) -> u64 {
values.iter().sum()
}
fn bench_sum(c: &mut Criterion) {
let data: Vec<u64> = (0..10_000).collect();
c.bench_function("sum 10k", |b| b.iter(|| sum_slice(black_box(&data))));
}
criterion_group!(benches, bench_sum);
criterion_main!(benches);The vector is built in setup, outside the timed closure. Without black_box, the optimizer could hoist sum_slice(&data) out of the loop, since data never changes between iterations. Wrapping the reference tells the compiler that something might change the data, so it must recompute the sum every time.
Wrap the reference, not a copy of the data. black_box(data.clone()) would put an allocation and a copy inside your measurement. The next chapters cover how to move that kind of cost out with iter_batched.
Outputs
Wrap results the benchmark would otherwise throw away, so the compiler cannot delete the computation as dead code. With Bencher::iter, you get this for free for the closure's return value. Criterion passes whatever the closure returns through black_box itself.
use criterion::{criterion_group, criterion_main, Criterion};
fn bench_returned(c: &mut Criterion) {
let data: Vec<u64> = (0..10_000).collect();
c.bench_function("sum returned", |b| {
// No semicolon: the value is returned, and Criterion protects it.
b.iter(|| data.iter().sum::<u64>())
});
}
criterion_group!(benches, bench_returned);
criterion_main!(benches);A trailing semicolon changes this. The closure then returns (), and the sum is a value nobody uses.
use criterion::{criterion_group, criterion_main, Criterion};
fn bench_discarded(c: &mut Criterion) {
let data: Vec<u64> = (0..10_000).collect();
c.bench_function("sum discarded", |b| {
b.iter(|| {
let _total: u64 = data.iter().sum();
})
});
}
criterion_group!(benches, bench_discarded);
criterion_main!(benches);The result is computed and dropped. The optimizer is free to remove the whole body. In this example the second benchmark may report a time near zero. Return the value from the closure, or wrap it with black_box yourself, whenever you need the work to survive.
Which values to wrap
| Situation | What to do |
|---|---|
| Literal or constant argument | Wrap the argument: `f(black_box(20))` |
| Large input built in setup | Wrap a reference to it: `f(black_box(&data))` |
| Result returned from the `iter` closure | Nothing extra. Criterion wraps it. |
| Result you store or discard inside the closure | Wrap it: `black_box(result);` |
| Input you need to modify per iteration | Use `iter_batched`, with the setup in its own closure |
Where black_box does not help
black_box is a hint to the compiler, not a guarantee of how real code would behave. Know its limits.
- It does not stop optimization inside the function you call. The compiler still optimizes
square_sumas hard as it can. That is what you want, because you are measuring the optimized function. It only stops the optimizer from using knowledge about the arguments or result. - It is not free. Each call forces a value into memory, so for operations that take a few nanoseconds the overhead shows up in the numbers. Do not sprinkle it around code you are timing. Use it at the boundary, once per input and once per output.
- It does not make results representative. A function called with a fixed input in a tight loop gets perfect branch prediction and warm caches. The real program may see neither. Varied inputs, covered in the groups chapter, help here.
- The effect is best-effort. The documentation for the standard library version states it is a hint and that its exact behavior may differ between platforms. Treat a surprisingly fast result as a signal to check, not as proof of a fast function.
Checking your work
You can tell whether the optimizer removed your work in three ways.
- Sanity-check the magnitude. A single addition costs around a nanosecond or less. A loop over 1000 elements cannot. Compare the time to a rough count of operations.
- Change the input size. Run the benchmark with input 1000 and 2000. If the time does not grow, the work is not scaling with the input and is probably computed ahead of time.
- Look at the assembly. The
cargo-show-asmtool prints the optimized code for a function. If the benchmark closure contains only a constant or a return, the work is gone.
cargo install cargo-show-asm
cargo asm --bench square_benchThe second command lists the functions it can display from that bench target. Pick one from the list, as the tool's output instructs.
How the pieces fit together
A checklist for each benchmark
Before you trust a number, ask these questions about the closure you pass to iter:
- Is every input either truly runtime data or wrapped in
black_box? - Is the result returned from the closure, or wrapped, so it counts as used?
- Does the closure do only the work you want to measure, with setup outside it?
- Does the time scale sensibly if you double the input size?
- Does the magnitude match a rough count of the operations involved?
Exercise
A benchmark contains b.iter(|| { let r = expensive(black_box(&input)); }) and reports a time close to zero. Why, and how do you fix it?
Show answer
The closure ends with a semicolon after the let, so it returns () and the value r is never used. The compiler can treat the call to expensive as dead code, provided it can prove the function has no side effects. Black-boxing the input does not help, because the result is still discarded. Fix it by returning the value from the closure (b.iter(|| expensive(black_box(&input)))) so Criterion passes it through black_box, or by writing black_box(r); inside the closure.
Exercise
You benchmark parse(black_box(text.clone())) on a 1 MB string and the result is dominated by memory copying instead of parsing. What went wrong, and what should you do instead?
Show answer
clone runs inside the timed closure, so the copy is part of the measurement. black_box hides the value from the optimizer but does not exclude the cost of creating it. Pass a reference with black_box(&text) if parse only needs to read the text. If it needs an owned value, use iter_batched with a setup closure that clones, so the clone is not timed.