Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benchmarking programs in Rust

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

like image 879
php-- Avatar asked Nov 10 '12 13:11

php--


People also ask

Does rust have a benchmark?

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.

What is benchmarking used for?

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.


2 Answers

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); } 
like image 29
ideasman42 Avatar answered Oct 17 '22 06:10

ideasman42


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:

  • The Rust Book (section on benchmark tests)
  • "The Nightly Book" (section on the test crate)
  • test::Bencher docs
like image 143
Michael Tang Avatar answered Oct 17 '22 07:10

Michael Tang