Home
Rust
Instant now, elapsed Example
Updated Oct 21, 2024
Dot Net Perls
Instant now. 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.
Example. This program uses Instant now twice, and then accesses methods on the Instant structs returned. The elapsed() method is most commonly used.
Part 1 Please make sure to add the "use" statement at the top of the program before calling Instant now in this way. We capture the current time.
Part 2 Just for this example program, we do some slow computations with a HashMap. This seems to require 4 ms in a release build.
Part 3 We can print the elapsed Duration with formatting codes in println, or we can access methods like as_millis() and get an integral number.
Part 4 The 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
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Oct 21, 2024 (new).
Home
Changes
© 2007-2025 Sam Allen