How much time has passed between one part of a function and another part? With Instant now, we can capture the current time, and compute an elapsed duration of time.
By calling the elapsed()
function, we can determine a duration of time that has passed. On Duration, we can use methods like as_millis()
to get an integral number.
This program uses Instant now twice, and then accesses methods on the Instant structs returned. The elapsed()
method is most commonly used.
HashMap
. This seems to require 4 ms in a release build.println
, or we can access methods like as_millis()
and get an integral number.duration_since
computes the elapsed time between 2 Instants. This can be used to time code. The original Instant could also be used.use std::time::*; fn main() { // Part 1: call Instant now to capture current time. let t0 = Instant::now(); // Part 2: do some slow calculations (the effect is not important). let mut h = std::collections::HashMap::new(); for i in 0..100000 { h.insert(i, "?"); } // Part 3: print elapsed duration in a variety of ways. println!("ELAPSED: {:?}", t0.elapsed()); println!("{}", t0.elapsed().as_nanos()); println!("{}", t0.elapsed().as_millis()); println!("{}", t0.elapsed().as_micros()); println!("{}", t0.elapsed().as_secs()); // Part 4: get another Instant, and compute the duration since the previous instant. let t1 = Instant::now(); let result = t1.duration_since(t0); println!("DURATION SINCE: {:?}", result); println!("ELAPSED: {:?}", t0.elapsed()); }ELAPSED: 3.0713ms 3208500 3 3863 0 DURATION SINCE: 4.3297ms ELAPSED: 4.4323ms
For timing code, or even external operations like network requests, Instant now is a good choice in Rust. With elapsed()
and duration_since()
we can compute the time that has passed.