Rust program to measure the elapsed time of a function

Rust Example: Write a program to measure the elapsed time of a function.
Submitted by Nidhi, on November 25, 2021

Problem Solution:

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

Program/Source Code:

The source code to measure the elapsed time of a function is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.

// 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);
}

Output:

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

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.

Rust Miscellaneous Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.