How is it possible to benchmark programs in Rust? For example, how would I get execution time of program in seconds?
Rust's built-in benchmark tests are a simple starting point, but they use unstable features and only work on Nightly Rust. The bencher crate is similar but works with stable Rust. Criterion is a more sophisticated alternative. Custom benchmarking harnesses are also possible.
Businesses can use benchmarking in their operations to measure themselves against internal or external standards. Benchmarking can be used to measure internal progress, performance against competitors and how your processes rank against world-class organizations.
For measuring time without adding third-party dependencies, you can use std::time::Instant
:
fn main() { use std::time::Instant; let now = Instant::now(); // Code block to measure. { my_function_to_measure(); } let elapsed = now.elapsed(); println!("Elapsed: {:.2?}", elapsed); }
It might be worth noting two 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:
test
crate)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With