How to measure function execution time in Rust

1 Answer

0 votes
// Measuring function execution time in 
// Rust using a reusable Timer (milliseconds + seconds)

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

// ---------------------------
// Reusable Timer struct
// ---------------------------
struct Timer {
    start: Instant,
    end: Instant,
}

impl Timer {
    // Start the timer
    fn start() -> Self {
        Timer {
            start: Instant::now(),
            end: Instant::now(),
        }
    }

    // Stop the timer
    fn stop(&mut self) {
        self.end = Instant::now();
    }

    // Return elapsed time in milliseconds
    fn elapsed_milliseconds(&self) -> f64 {
        let duration: Duration = self.end.duration_since(self.start);
        duration.as_secs_f64() * 1000.0
    }

    // Return elapsed time in seconds
    fn elapsed_seconds(&self) -> f64 {
        let duration: Duration = self.end.duration_since(self.start);
        duration.as_secs_f64()
    }
}

// ---------------------------
// Function to measure
// ---------------------------
fn work() {
    let mut sum: u64 = 0;
    for i in 0..100_000_000 {
        sum += i;
    }
    
     println!("sum = {:.3}", sum);
}

// ---------------------------
// Main program
// ---------------------------
fn main() {
    let mut t: Timer = Timer::start();

    work();

    t.stop();

    let ms: f64 = t.elapsed_milliseconds();
    let sec: f64 = t.elapsed_seconds();

    println!("Execution time: {:.3} ms", ms);
    println!("Execution time: {:.6} seconds", sec);
}



/* 
run:

sum = 4999999950000000
Execution time: 714.921 ms
Execution time: 0.714921 seconds

*/

 



answered 4 hours ago by avibootz
...