name: benchmark-rust description: Write Rust benchmarks using Criterion.rs. Use when: user wants to benchmark Rust code, measure performance, optimize Rust programs, or compare implementations using Criterion's statistical analysis. license: MIT
Rust Benchmarking
This skill covers benchmarking Rust code using Criterion.rs and related tools.
Setup
Cargo.toml
[dev-dependencies]
criterion = { version = "0.5", features = ["html_reports", "plotters"] }
[[bench]]
name = "my_benchmark"
harness = false
Project Structure
src/
benches/
└── my_benchmark.rs # Your benchmarks here
Cargo.toml
Writing Benchmarks
Basic Benchmark
use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion};
fn fibonacci(n: u64) -> u64 {
match n {
0 => 0,
1 => 1,
_ => fibonacci(n - 1) + fibonacci(n - 2),
}
}
fn bench_fibonacci(c: &mut Criterion) {
c.bench_function("fibonacci_20", |b| {
b.iter(|| fibonacci(black_box(20)))
});
}
criterion_group!(benches, bench_fibonacci);
criterion_main!(benches);
Parameterized Benchmarks
fn bench_fibonacci_param(c: &mut Criterion) {
let mut group = c.benchmark_group("fibonacci");
for n in [10, 20, 30, 40].iter() {
group.bench_with_input(BenchmarkId::from_parameter(n), n, |b, &n| {
b.iter(|| fibonacci(black_box(n)))
});
}
group.finish();
}
Advanced: iter_batched
For setups that need preparation:
fn bench_sort(c: &mut Criterion) {
let sizes = [100, 1000, 10000];
c.bench_function_over_inputs("sort", |b, &&size| {
b.iter_batched(
|| (0..size).collect::<Vec<_>>(), // Setup
|mut v| v.sort(), // Benchmark
criterion::BatchSize::LargeInput, // Size hint
);
}, &sizes);
}
Preventing Compiler Optimizations
black_box
use std::hint::black_box;
// Prevent DCE - compiler can't see result is used
let result = expensive_computation();
black_box(result);
// Prevent constant folding - compiler can't predict value
let input = black_box(get_runtime_value());
Do Not Optimize (Alternative)
fn do_not_optimize<T>(val: T) -> T {
std::hint::black_box(val)
}
Running Benchmarks
Basic
cargo bench
Common Flags
cargo bench --release # Optimized build (always use!)
cargo bench -- --noplot # No plotting, text output
cargo bench -- --profile # Generate profiles
cargo bench --bench my_benchmark # Run specific benchmark
cargo bench -- --test # Quick correctness check
Output Interpretation
fibonacci_20 time: [25.123 us 25.456 us 25.789 us]
thrpt: 39,234 ops/s
Shows mean, confidence interval, and throughput.
Configuration
criterion.toml
[benchmarks]
warm_up_time = "2s"
measurement_time = "5s"
sample_size = 100
noise_threshold = 0.01
[benchmarks.plot]
colors = true
Memory Benchmarking: Iai
For memory/instruction counting (stable across runs):
[dev-dependencies]
iai = "0.1"
[[bench]]
name = "my_memory_bench"
harness = false
use iai::black_box;
fn fibonacci(n: u64) -> u64 {
match n {
0 => 0,
1 => 1,
_ => fibonacci(n - 1) + fibonacci(n - 2),
}
}
iai::bench!(|| fibonacci(black_box(20)));
Profiling Rust
cargo-flamegraph (Recommended)
cargo install flamegraph
# CPU profile
cargo flamegraph --bin my_app
# Memory profile
cargo flamegraph --bin my_app --memory
# To file
cargo flamegraph -o flamegraph.svg --bin my_app
Linux perf
perf record -g ./target/release/my_benchmark
perf report
perf script | flamegraph.pl > flamegraph.svg
Valgrind (Memory Leaks)
valgrind --tool=massif ./target/release/my_benchmark
ms_print massif.out.xxxx
Common Pitfalls
- Always use
--release- Debug builds are meaningless - Use black_box - Prevents DCE and constant folding
- Warm up - Criterion does this automatically
- Check allocation - Use
--features benchor manual counting - Don't benchmark from tests - Use criterion, not #[test]
Quick Reference
| Task | Command |
|---|---|
| Run benchmarks | cargo bench |
| Single benchmark | cargo bench --bench my_bench |
| Generate HTML | cargo bench -- --plot (enabled by default with html_reports) |
| Profile CPU | cargo flamegraph --bin my_app |
| Profile memory | cargo flamegraph --bin my_app --memory |
| Iai memory | cargo bench --bench my_iai_bench |