Benchmarking programs in Rust

前端 未结 8 1179
礼貌的吻别
礼貌的吻别 2020-12-07 23:50

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

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-08 00:28

    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:

    • The Rust Book (section on benchmark tests)
    • "The Nightly Book" (section on the test crate)
    • test::Bencher docs

提交回复
热议问题