Skip to content

Commit 24831c7

Browse files
committed
Auto merge of #44436 - MicroJoe:master, r=alexcrichton
Add Duration::from_micros This fixes #44400 that explains why it could be useful for embedded designs timing.
2 parents 26015da + b40a9f4 commit 24831c7

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_MICRO: 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.
@@ -116,6 +118,27 @@ impl Duration {
116118
Duration { secs: secs, nanos: nanos }
117119
}
118120

121+
/// Creates a new `Duration` from the specified number of microseconds.
122+
///
123+
/// # Examples
124+
///
125+
/// ```
126+
/// #![feature(duration_from_micros)]
127+
/// use std::time::Duration;
128+
///
129+
/// let duration = Duration::from_micros(1_000_002);
130+
///
131+
/// assert_eq!(1, duration.as_secs());
132+
/// assert_eq!(2000, duration.subsec_nanos());
133+
/// ```
134+
#[unstable(feature = "duration_from_micros", issue = "44400")]
135+
#[inline]
136+
pub fn from_micros(micros: u64) -> Duration {
137+
let secs = micros / MICROS_PER_SEC;
138+
let nanos = ((micros % MICROS_PER_SEC) as u32) * NANOS_PER_MICRO;
139+
Duration { secs: secs, nanos: nanos }
140+
}
141+
119142
/// Returns the number of _whole_ seconds contained by this `Duration`.
120143
///
121144
/// The returned value does not include the fractional (nanosecond) part of the

0 commit comments

Comments
 (0)