Time and durations
Quick answer
Use Duration for a nonnegative amount of time, Instant for elapsed-time measurement, and SystemTime for a wall-clock timestamp. These types serve different purposes and should not be mixed casually.
Monotonic versus wall time
Instant represents a monotonic-clock reading intended for measuring intervals, not a calendar date. SystemTime can move backward when the clock is adjusted; duration_since returns a Result. Use checked arithmetic for durations derived from untrusted input. Avoid timing assertions that depend on the machine's load.
use std::time::Duration;fn main() { let total = Duration::from_secs(2) + Duration::from_millis(250); println!("{} ms", total.as_millis()); }Expected stdout (not executed):
2250 msThe calculation uses fixed values, not the current clock.
use std::time::{Duration, UNIX_EPOCH};fn main() { let later = UNIX_EPOCH + Duration::from_secs(10); println!("{}", later.duration_since(UNIX_EPOCH).unwrap().as_secs()); println!("reversed: {}", UNIX_EPOCH.duration_since(later).is_err()); }Expected stdout (not executed):
10reversed: trueReversed wall-clock subtraction is fallible.
Common mistake
Duration is not a signed calendar interval, and SystemTime is not a monotonic stopwatch.
Try it yourself
Convert 1500 milliseconds into whole seconds and remaining milliseconds using Duration.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Time and durations — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A wall clock is adjusted while measuring a task. Which clock should the duration measurement use?
Time and durations — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::time::Duration; fn main() { let total = Duration::from_secs(2) + Duration::from_millis(250); println!("{} ms", total.as_millis()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Time and durations — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::time::{Duration, UNIX_EPOCH}; fn main() { let later = UNIX_EPOCH + Duration::from_secs(10); println!("{}", later.duration_since(UNIX_EPOCH).unwrap().as_secs()); println!("reversed: {}", UNIX_EPOCH.duration_since(later).is_err()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.