Time
| SystemTime::now | |
| Instant stopwatches | |
| Duration math | |
| Elapsed helper |
SystemTime::now
The clock on the wall is SystemTime, and now reads it. The value is opaque on purpose, because wall clocks can jump backwards:
use std::time::SystemTime;
fn main() {
let start = SystemTime::now();
println!("{:?}", start);
}
Debug output shows the raw timestamp. SystemTime is for talking to the outside world, never for measuring speed.
Instant stopwatches
For measuring speed use Instant, a stopwatch that only moves forward. Read it once, do the work, then ask how much time passed:
use std::time::Instant;
fn main() {
let t0 = Instant::now();
let mut sum: u64 = 0;
for i in 0..1000 {
sum += i;
}
println!("sum: {} in {:?}", sum, t0.elapsed());
}
Duration math
A Duration is a span of time with friendly constructors. Build values, add them, and read them back in any unit you need:
use std::time::Duration;
fn main() {
let wait = Duration::from_secs(2) + Duration::from_millis(500);
println!("secs: {}", wait.as_secs());
println!("millis: {}", wait.as_millis());
}
Adding durations is plain addition with plus. Convert with as_secs or as_millis depending on the precision you need.
Elapsed helper
Most programs repeat the same stopwatch dance, so wrap it in a helper. Pass the start time by reference and get seconds back as a float:
use std::time::Instant;
fn elapsed_secs(t0: &Instant) -> f64 {
t0.elapsed().as_secs_f64()
}
fn main() {
let t0 = Instant::now();
println!("lap: {}", elapsed_secs(&t0));
}
One helper keeps every benchmark in the program consistent. Parsing lessons next give the stopwatch something to measure.
Next: Parsing strings
Article author: Arthur Isaev