Hi, I'm new to Rust and is trying to figure out a way to test the speed of my function.
Something like:
pub fn test_function(...)->...{}
pub fn testspeed(){
println!("start");
let now = Instant::now();
let mut i:u128=10000000000;
while i!=0{
i-=1;
test_function();
}
let elapsed_time = now.elapsed();
println!("end");
println!("Running it took {:?} seconds.", elapsed_time);
}
How ever If I then use cargo r --release, it would directly skip the loop. I know it's useful but how can I run the loop with the least code other than test_function()?
Thank you for any thoughts!
Sounds like your loop was optimized out for being a no-op. Maybe you can have the function return some value it has computed and then print the sum of those values at the end?
On nightly, you can use std::hint::black_box to do something similar without the overhead of addition:
#![feature(bench_black_box)]
use time::Instant;
pub fn test_function()->u32{ 0}
pub fn testspeed(){
println!("start");
let now = Instant::now();
for _ in 0..10000000000u128 {
std::hint::black_box(test_function());
}
let elapsed_time = now.elapsed();
println!("end");
println!("Running it took {:?} seconds.", elapsed_time);
}