std::time is Rust’s minimal standard-library module for measuring elapsed time and reading system-clock time. Its useful building blocks include Instant, Duration, and SystemTime. section 17.2
Use its types for focused timing tasks:
- Instant::now() captures an opaque point based on system uptime, so it is useful for benchmarks and measuring operation length, not calendar dates. section 17.2
- Subtracting two Instants, or calling elapsed(), produces a Duration describing the time between them. section 17.2
- SystemTime represents the system clock, while UNIX_EPOCH lets a program measure time from a fixed epoch. section 17.2
Pause execution with Duration
Create a Duration with Duration::from_secs(3), pass it to thread::sleep, and continue after the pause. This demonstrates Duration as a reusable amount of time rather than a clock reading.
use std::time::Instant;
fn main() {
let start = Instant::now();
println!("Time elapsed before busy operation: {:?}", start.elapsed());
let mut new_string = String::new();
loop {
new_string.push('წ');
if new_string.len() > 100_000 {
break;
}
}
println!("Operation complete. Time elapsed: {:?}", start.elapsed());
}
Inspect a complete elapsed-time example that records an Instant, performs a busy operation, and reports start.elapsed(). section 17.2
