Benchmarking programs in Rust

php-- picture php-- · Nov 10, 2012 · Viewed 27.7k times · Source

How is it possible to benchmark programs in Rust? For example, how would I get execution time of program in seconds?

Answer

Michael Tang picture Michael Tang · Oct 9, 2014

It might be worth noting 2 years later (to help any future Rust programmers who stumble on this page) that there are now tools to benchmark Rust code as a part of one's test suite.

(From the guide link below) Using the #[bench] attribute, one can use the standard Rust tooling to benchmark methods in their code.

extern crate test;
use test::Bencher;

#[bench]
fn bench_xor_1000_ints(b: &mut Bencher) {
    b.iter(|| {
        // use `test::black_box` to prevent compiler optimizations from disregarding
        // unused values
        test::black_box(range(0u, 1000).fold(0, |old, new| old ^ new));
    });
}

For the command cargo bench this outputs something like:

running 1 test
test bench_xor_1000_ints ... bench:       375 ns/iter (+/- 148)

test result: ok. 0 passed; 0 failed; 0 ignored; 1 measured

Links: