Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Standard Library Modules

Rust Duration type

Reference for std::time::Duration: constructors, accessors like as_secs and subsec_nanos, checked and saturating arithmetic, float conversion, Debug output and panics.

std::time::Duration is a span of time: a whole number of seconds (u64) plus a number of extra nanoseconds (u32, always below one billion). It is never negative, it is Copy, and it supports +, -, * and / with plain integers. Durations are what you pass to thread::sleep, recv_timeout, Condvar::wait_timeout and socket timeouts, and what you get back from Instant::elapsed.

Because the value is stored as seconds and nanoseconds, there is no rounding when you build one from integers. Floating-point constructors do round, to the nearest nanosecond.

Rust
use std::time::Duration;

let timeout = Duration::from_millis(1_500);

Try it

Rust Build, inspect and print durations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Checked, saturating and float math

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Overflow panics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
pub struct Duration { /* secs: u64, nanos: u32 */ }

impl Duration {
    pub const ZERO: Duration;
    pub const MAX: Duration;
    pub const fn new(secs: u64, nanos: u32) -> Duration;
    pub const fn from_secs(secs: u64) -> Duration;
    pub const fn from_millis(ms: u64) -> Duration;
    pub const fn from_micros(us: u64) -> Duration;
    pub const fn from_nanos(ns: u64) -> Duration;
    pub fn from_secs_f64(secs: f64) -> Duration;
    pub fn from_secs_f32(secs: f32) -> Duration;
    pub fn try_from_secs_f64(secs: f64) -> Result<Duration, TryFromFloatSecsError>;
    pub const fn as_secs(&self) -> u64;
    pub const fn as_millis(&self) -> u128;
    pub const fn as_micros(&self) -> u128;
    pub const fn as_nanos(&self) -> u128;
    pub const fn subsec_millis(&self) -> u32;
    pub const fn subsec_micros(&self) -> u32;
    pub const fn subsec_nanos(&self) -> u32;
    pub fn as_secs_f64(&self) -> f64;
    pub fn as_secs_f32(&self) -> f32;
    pub const fn checked_add(self, rhs: Duration) -> Option<Duration>;
    pub const fn checked_sub(self, rhs: Duration) -> Option<Duration>;
    pub const fn checked_mul(self, rhs: u32) -> Option<Duration>;
    pub const fn checked_div(self, rhs: u32) -> Option<Duration>;
    pub const fn saturating_add(self, rhs: Duration) -> Duration;
    pub const fn saturating_sub(self, rhs: Duration) -> Duration;
    pub const fn abs_diff(self, other: Duration) -> Duration;
    pub fn mul_f64(self, rhs: f64) -> Duration;
    pub fn div_f64(self, rhs: f64) -> Duration;
    pub const fn is_zero(&self) -> bool;
}
Name Description
secs, nanos Whole seconds and extra nanoseconds. new carries nanoseconds above 999,999,999 into the seconds.
rhs (for * and /) A u32. For fractional factors use mul_f64 or div_f64.
Duration::MAX About 584 billion years (u64::MAX seconds plus 999,999,999 ns).

Returns. The as_* methods truncate (1.9 s gives as_secs() == 1); as_millis, as_micros and as_nanos return u128 so they never overflow. subsec_* give only the fractional part, not the total.

Errors and panics.

  • +, -, * and / panic on overflow, on subtraction that would go below zero, and on division by zero. Use the checked_* or saturating_* forms for untrusted input.
  • new panics if carrying the nanoseconds overflows the seconds field.
  • from_secs_f64 and friends panic for negative, NaN or too-large values; try_from_secs_f64 returns an error instead.

Usage notes

  • Debug output picks a readable unit: 90s, 1.5s, 250ยตs, 42ns. It is meant for logs, not parsing. {:.2?} limits the fractional digits, which is handy for timings. Duration does not implement Display.
  • Comparison. Duration implements Ord and Hash, so it works as a BTreeMap key and with max, min and sort.
  • Summing. Iterator::sum works on iterators of Duration and &Duration; it panics on overflow like +.
  • No calendar. A Duration is an exact count of seconds. It knows nothing about days with 23 or 25 hours, months or leap years. Use a date-time crate for that.
  • as_secs_f64 is lossy for very large or very precise values, because f64 has 53 bits of precision.
  • Integer widths. from_millis takes u64, but as_millis returns u128. Cast with u64::try_from(d.as_millis()) when an API wants a smaller type.
  • Helpers added later. Recent releases added from_mins and from_hours constructors; if you must support older compilers, use from_secs(n * 60).
  • Timeouts. A zero duration is legal almost everywhere, but a few socket APIs reject Duration::ZERO as a timeout with InvalidInput.