liveBook · Manning

Black_box

As explained in Refactoring to Rust

criterion::black_box provides an opaque value boundary intended to prevent compiler optimization from eliminating benchmarked code.

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()));

How Refactoring to Rust covers it

How deep it goes
Defines placement inside b.iter but does not explain compiler internals or the implementation of the opaque boundary.
Examples
Demonstrates black_box with 3u8 + 4, 3u128 + 4, and results returned by py.run.
What it assumes
Assumes familiarity with Criterion's b.iter closure and introduces black_box through small arithmetic and Python benchmark examples.
What you can do after
Apply it via Criterion by passing benchmark results through black_box inside b.iter.
How it connects
Connects Criterion, benchmarking, compiler optimization, and PyO3-based Python execution.

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.