Skip to content

Commit 4db499f

Browse files
committed
Add Duration::from_micros
1 parent dead08c commit 4db499f

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

src/libstd/time/duration.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@ use ops::{Add, Sub, Mul, Div, AddAssign, SubAssign, MulAssign, DivAssign};
1313

1414
const NANOS_PER_SEC: u32 = 1_000_000_000;
1515
const NANOS_PER_MILLI: u32 = 1_000_000;
16+
const NANOS_PER_MICROS: u32 = 1_000;
1617
const MILLIS_PER_SEC: u64 = 1_000;
18+
const MICROS_PER_SEC: u64 = 1_000_000;
1719

1820
/// A `Duration` type to represent a span of time, typically used for system
1921
/// timeouts.
@@ -114,6 +116,27 @@ impl Duration {
114116
let secs = millis / MILLIS_PER_SEC;
115117
let nanos = ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI;
116118
Duration { secs: secs, nanos: nanos }
119+
120+
/// Creates a new `Duration` from the specified number of microseconds.
121+
///
122+
/// # Examples
123+
///
124+
/// ```
125+
/// use std::time::Duration;
126+
///
127+
/// let duration = Duration::from_micros(1_000_002);
128+
///
129+
/// assert_eq!(1, duration.as_secs());
130+
/// assert_eq!(2000, duration.subsec_nanos());
131+
/// ```
132+
#[inline]
133+
pub fn from_micros(micros: u64) -> Duration {
134+
let secs = micros / MICROS_PER_SEC;
135+
let nanos = ((micros % MICROS_PER_SEC) as u32) * NANOS_PER_MICRO;
136+
Duration {
137+
secs: secs,
138+
nanos: nanos,
139+
}
117140
}
118141

119142
/// Returns the number of _whole_ seconds contained by this `Duration`.

0 commit comments

Comments
 (0)