duration
import std::time::duration; · source
Duration
type struct Duration {
secs: u64;
nanos: u32;
static new(secs: u64, nanos: u32) -> Duration;
static zero() -> Duration;
static second() -> Duration;
static millisecond() -> Duration;
static microsecond() -> Duration;
static nanosecond() -> Duration;
static from_secs(secs: u64) -> Duration;
static from_millis(millis: u64) -> Duration;
static from_micros(micros: u64) -> Duration;
static from_nanos(nanos: u64) -> Duration;
static from_secs_f64(secs: f64) -> Duration;
as_secs(&this) -> u64;
subsec_nanos(&this) -> u32;
subsec_millis(&this) -> u32;
subsec_micros(&this) -> u32;
as_millis(&this) -> u64;
as_micros(&this) -> u64;
as_nanos(&this) -> u64;
as_secs_f64(&this) -> f64;
is_zero(&this) -> boolean;
checked_add(&this, other: &Duration) -> Option<Duration>;
checked_sub(&this, other: &Duration) -> Option<Duration>;
saturating_add(&this, other: &Duration) -> Duration;
saturating_sub(&this, other: &Duration) -> Duration;
scale(&this, factor: u64) -> Duration;
mul_f64(&this, factor: f64) -> Duration;
divide(&this, divisor: u64) -> Duration;
to_string(&this) -> String;
to_debug_string(&this) -> String;
}
Whole seconds plus a sub-second nanosecond remainder, always normalized so that nanos < 1_000_000_000.
import std::time;
const timeout: Duration = Duration::from_millis(250);
sleep(timeout);
Building
new(secs, nanos) carries any nanosecond overflow into the seconds field, so the stored value is always normalized. Then the unit constructors — from_secs, from_millis, from_micros, from_nanos, and from_secs_f64 (negative input clamps to zero) — plus the named constants zero(), second(), millisecond(), microsecond(), and nanosecond().
Reading
| Method | Returns |
|---|---|
as_secs() | Whole seconds; the sub-second part is dropped. |
as_millis() / as_micros() / as_nanos() | The whole span in that unit. |
as_secs_f64() | The whole span as fractional seconds. |
subsec_nanos() / subsec_millis() / subsec_micros() | Just the remainder. |
is_zero() | boolean |
Arithmetic
checked_add and checked_sub return Option<Duration>, None on overflow or underflow. saturating_add and saturating_sub clamp instead. scale(factor), mul_f64(factor), and divide(divisor) scale the span; mul_f64 clamps a negative factor to zero.
to_string() renders in the largest sensible unit — 1.5s, 250ms, 10ns — the same text as the Display impl, and to_debug_string() the Debug form.
Trait implementations
implement trait Eq for struct Duration
implement trait Ord for struct Duration
implement trait Display for struct Duration
implement trait Debug for struct Duration