How to Benchmark Code in Rust

Use the Criterion crate with `cargo bench` to measure and compare the execution speed of your Rust functions.

Use the criterion crate to benchmark Rust code, as the built-in cargo bench command is deprecated. Add criterion to your Cargo.toml dependencies, create a benches directory, and write a benchmark function using the criterion_group! and criterion_main! macros.

[dev-dependencies]
criterion = "0.5"

[[bench]]
name = "my_benchmark"
harness = false
// benches/my_benchmark.rs
use criterion::{black_box, criterion_group, criterion_main, Criterion};

fn add(left: u64, right: u64) -> u64 {
    left + right
}

fn criterion_benchmark(c: &mut Criterion) {
    c.bench_function("add", |b| b.iter(|| add(black_box(2), black_box(2))));
}

criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);

Run the benchmark with cargo bench --bench my_benchmark.