Measure the elapsed time of a function
Rust Programming Language
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 functionuse 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 WorldTime 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.