- Instant
- now
- elapsed
- std::time::Instant::now
- as_secs
- as_millis
Measure elapsed time
- std::time
- The Instant type allows us to get snapshots if time that can help us measure elapesd time.
- In this example we have a function to decide if a number is a prime number. We only use it to have some code that can take substantial time.
- We get the timestamp before and after and we calculate the elapsed time.
examples/datetime/instant-elapsed/src/main.rs
fn main() { let start = std::time::Instant::now(); for number in 2..=100000 { let _prime = is_prime(number); //println!("{} {}", number, prime); } let end = std::time::Instant::now(); println!("{:?}", start); println!("{:?}", end); let elapsed = end - start; println!("{:?}", elapsed); println!("{:?}", start.elapsed()); println!("milliseconds: {:?}", start.elapsed().as_millis()); println!("seconds: {:?}", start.elapsed().as_secs()); } fn is_prime(number: u32) -> bool { for div in 2..number { if number % div == 0 { return false; } } true }
Instant { tv_sec: 5094523, tv_nsec: 863978009 } Instant { tv_sec: 5094525, tv_nsec: 872085539 } 2.00810753s 2.008157397s milliseconds: 2008 seconds: 2