How to test speed?

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?

2 Likes

The best way is probably to use a benchmarking framework like Criterion instead of trying to measure the timings yourself.

3 Likes

I've tried that, and it works! but to add up results takes time, is there any way else?

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);
}
2 Likes

Oh thanks! It works fine!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.