liveBook · Manning

Cargo bench

As explained in Idiomatic Rust

cargo bench is a Cargo command that compiles benchmarks in release mode and executes them.

cargo bench compiles benchmarks in release mode and runs them. The built-in benchmarking feature shown here requires nightly Rust, and these benchmarks run with cargo bench rather than cargo test. section 10.4

Listing 10.7 Benchmarking Vec, HashSet, and LinkedList for appending
#[bench]
fn vec_append(b: &mut Bencher) {
    b.iter(|| {
        let mut nums: Vec<i32> = Vec::new();
        for n in 0..1_000_000 {
            nums.push(n);
        }
    });
}

#[bench]
fn list_append(b: &mut Bencher) {
    b.iter(|| {
        let mut nums: LinkedList<i32> = LinkedList::new();
        for n in 0..1_000_000 {
            nums.push_back(n);
        }
    });
}

#[bench]
fn set_append(b: &mut Bencher) {
    b.iter(|| {
        let mut nums: HashSet<i32> = HashSet::new();
        for n in 0..1_000_000 {
            nums.insert(n);
        }
    });
}

The example times appending one million integers to a Vec, LinkedList, and HashSet using #[bench] and Bencher. section 10.4

Comparing append timings

In one reported run, Vec append took about 2.1 ms per iteration, compared with about 53.9 ms for LinkedList. Results can vary by machine. section 10.4

How Idiomatic Rust covers it

How deep it goes
Shows #[bench] functions using Bencher and sample timings, while leaving the full benchmark suite elsewhere.
Examples
Benchmarks appending one million elements and finding or removing values in million-element collections.
What you can do after
Evaluate collection performance by running benchmarks and comparing measured timings, while allowing for machine-to-machine variation.
How it connects
Connects benchmarking with Vec, HashSet, and LinkedList performance comparisons.

Also explained in

Compare how 2 books explain cargo bench →

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