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 have a [[bench]] target with harness = false. Here you learn why the optimizer can make a benchmark meaningless, and how black_box prevents that.
The problem: the compiler can delete your work
Benchmarks run in release mode (cargo bench uses an optimized profile). The optimizer knows the code you are timing, and it is allowed to change anything that does not change the program's visible behavior. If a benchmark computes a value that nobody uses, or computes it from a constant, the compiler can remove or precompute the work.
Two things usually go wrong:
- Constant folding. The input is a literal such as
20. The compiler evaluatesfibonacci(20)at compile time, and the benchmark times an empty loop. - Dead code elimination. The result is thrown away. The compiler sees no side effects and drops the call.
The symptom is a time that looks too good: a fraction of a nanosecond for work that should take microseconds. Treat any result under about one nanosecond with suspicion.
What black_box does
black_box is an identity function. It returns its argument unchanged. Its purpose is to be opaque to the optimizer. The compiler must assume the value could be read or changed in ways it cannot see, so it cannot fold the value into a constant or assume it is unused.
Criterion re-exports black_box from criterion. Recent Rust versions also provide std::hint::black_box, which works the same way for this purpose.
use criterion::{black_box, criterion_group, criterion_main, Criterion};
fn fibonacci(n: u64) -> u64 {
match n {
0 | 1 => 1,
n => fibonacci(n - 1) + fibonacci(n - 2),
}
}
fn bench_fib(c: &mut Criterion) {
c.bench_function("fib 20", |b| b.iter(|| fibonacci(black_box(20))));
}
criterion_group!(benches, bench_fib);
criterion_main!(benches);Here black_box(20) hides the input, so the compiler cannot compute fibonacci(20) ahead of time. The function runs on every iteration.
Protecting the output
Wrapping the input stops constant folding. The output is a separate concern. Bencher::iter already passes the closure's return value to black_box for you, so returning the result from the closure is enough:
b.iter(|| fibonacci(black_box(20)))The closure has no trailing semicolon, so the value is returned and kept alive. If you add a semicolon, the closure returns () and the result is discarded:
b.iter(|| { fibonacci(black_box(20)); })Criterion's protection of the return value then has nothing to protect. Whether the compiler removes the call depends on what it can prove about the function. Do not rely on luck. Return the value.
In setups where you cannot return the value, such as iter_batched when the routine consumes its input, wrap the result yourself. The sorting benchmark from the setup chapters does this:
|mut v| {
v.sort();
black_box(v)
}Where to place black_box
Apply it to each input the compiler could otherwise treat as a known constant, and to each result you do not return.
use criterion::{black_box, criterion_group, criterion_main, Criterion};
fn sum_to(n: u64) -> u64 {
(0..n).sum()
}
fn bench_sum(c: &mut Criterion) {
c.bench_function("sum_to 10000", |b| {
b.iter(|| sum_to(black_box(10_000)))
});
}
criterion_group!(benches, bench_sum);
criterion_main!(benches);Without black_box, the optimizer can replace a simple summing loop with a closed-form formula or a constant. The measured time would describe that replacement, not the loop you wrote.
Limits of black_box
black_box is a best-effort hint. It does not make the benchmark realistic.
- It hides the value, but the surrounding code is still optimized. This is usually what you want, because it matches production builds.
- It adds a small cost. For very fast functions, this cost is part of the measurement.
- It cannot fix a benchmark that measures the wrong thing. If the input is unrealistic, the result is too.
Checking a suspicious result
- Run the benchmark and note the time.
- Wrap the input in
black_boxand make sure the closure returns the result. - Run again. If the time rises sharply, the compiler had been removing work.
Exercise
A benchmark is written as b.iter(|| { compute(black_box(100)); }) and reports 0.4 ns per iteration, which seems too fast. Name two likely causes and give one fix.
Show answer
The trailing semicolon makes the closure return (), so the result is discarded and the compiler may remove the call as dead code. Also, compute may be cheap enough that overhead dominates, or other arguments may be constant. Fix: remove the semicolon so the closure returns the value (b.iter(|| compute(black_box(100)))), then confirm the time rises to a realistic figure.