Rust Reference ยท Tools
cargo bench
Reference for cargo bench: run benchmarks, use Criterion or the unstable test harness, avoid optimizer traps with black_box and read timing results.
cargo bench compiles your benchmark targets with the bench profile (optimized, like release) and runs them. Benchmarks live in the benches/ directory, or in #[bench] functions inside the crate.
On stable Rust, the built-in #[bench] attribute is not available; the standard approach is a crate such as Criterion or Divan, with harness = false in Cargo.toml. The only piece of benchmarking support that is stable in the standard library is std::hint::black_box, which stops the optimizer from deleting the code you want to measure. This page is a read-only command reference; the examples use plain Instant timing without printing the timings themselves.
$ cargo bench $ cargo bench parse
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
cargo bench [options] [benchname] [-- <harness options>]
[[bench]] name = "parsing" harness = false # required for Criterion/Divan
| Name | Description |
|---|---|
benchname |
Run only benchmarks whose name contains this text. |
--bench name |
Run one bench target (a file in benches/). |
--no-run |
Compile benchmarks but do not run them. |
--profile |
Use a different profile than bench. |
-- --save-baseline x |
Criterion option after --: store results for later comparison. |
Usage notes
- The
benchprofile inherits fromrelease, so benchmarks are optimized with debug assertions off. Never benchmark a debug build. - Without
black_boxthe optimizer may compute a constant result at compile time and your benchmark measures nothing. - Run several iterations and report a distribution; one measurement is noise. Criterion does warm-up, sampling and statistics for you.
- Keep the machine quiet: close other programs, use a fixed power plan, and compare runs on the same hardware.
#[bench]andtest::Bencherneed a nightly compiler and#![feature(test)].- Benchmarks in
benches/can only use your crate's public API; put hot internals behind a small public function if you must measure them. - Measure first, optimize second: use a profiler (
perf, Instruments, flamegraph) to find which function matters.