This program uses Instant now twice, and then accesses methods on the Instant structs returned. The elapsed() method is most commonly 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