criterion::black_box creates an opaque value boundary for benchmarked code. Passing a computed result through it helps prevent the compiler from removing work that appears unused. section 6.5 section 6.7
Use black_box when:
- A value is computed inside b.iter and the final result would otherwise appear unused. section 6.5
- A benchmark executes Python through PyO3 and needs the result of py.run included in the measurement. section 6.5
Protecting a measured computation
use criterion::{black_box, Criterion}; c.bench_function("u8", |b| { b.iter(|| { black_box(3u8 + 4); }); }); The same pattern applies to other computations, such as 3u128 + 4. For Python execution, wrap the result similarly: b.iter(|| black_box(py.run(code, None, Some(&locals)).unwrap()));
