Rust program to measure the elapsed time of a function


Measure the elapsed time of a function

Rust Programming Language


Measure the elapsed time of a function


Problem


In this program, we will measure the elapsed time of a function using the Now() and elapsed() method of Instant.


Input


// Rust program to measure the 
// elapsed time of a function

use std::time::{Instant};
use std::thread;
use std::time::Duration;

fn my_fun(){
thread::sleep(Duration::from_millis(500));
    println!("Hello World"); 
}

fn main() {
    let current = Instant::now();
    
    my_fun();
    
    let duration = current.elapsed();
    
    println!("Time elapsed in MyFun() is: {:?}", duration);
}{codeBox}


Output


Hello World
Time elapsed in MyFun() is: 500.107266ms{codeBox}


Explanation


In the my_fun() function we stop the function for 500 milliseconds and printed "Hello World" message.

In the main() function, we called the Now() method to get the current time and used elapsed() method to get elapsed() time in calling of my_fun() function and printed the result.




Post a Comment