Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Duration::as_millis_{f64,f32} #122479

Merged
merged 1 commit into from
Mar 15, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
42 changes: 42 additions & 0 deletions library/core/src/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -856,6 +856,48 @@ impl Duration {
(self.secs as f32) + (self.nanos.0 as f32) / (NANOS_PER_SEC as f32)
}

/// Returns the number of milliseconds contained by this `Duration` as `f64`.
///
/// The returned value does include the fractional (nanosecond) part of the duration.
///
/// # Examples
/// ```
/// #![feature(duration_millis_float)]
/// use std::time::Duration;
///
/// let dur = Duration::new(2, 345_678_000);
/// assert_eq!(dur.as_millis_f64(), 2345.678);
/// ```
#[unstable(feature = "duration_millis_float", issue = "122451")]
#[must_use]
#[inline]
#[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")]
pub const fn as_millis_f64(&self) -> f64 {
(self.secs as f64) * (MILLIS_PER_SEC as f64)
+ (self.nanos.0 as f64) / (NANOS_PER_MILLI as f64)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was pondering whether this should be

Suggested change
+ (self.nanos.0 as f64) / (NANOS_PER_MILLI as f64)
+ (self.nanos.0 as f64) * (1.0 / (NANOS_PER_MILLI as f64))

because floating-point division is slow, but probably not because as_secs_f32 also does it this way.

Let's leave it like this for the PR; I'll add a note to the tracking issue for libs-api to consider some other time.

}

/// Returns the number of milliseconds contained by this `Duration` as `f32`.
///
/// The returned value does include the fractional (nanosecond) part of the duration.
///
/// # Examples
/// ```
/// #![feature(duration_millis_float)]
/// use std::time::Duration;
///
/// let dur = Duration::new(2, 345_678_000);
/// assert_eq!(dur.as_millis_f32(), 2345.678);
/// ```
#[unstable(feature = "duration_millis_float", issue = "122451")]
#[must_use]
#[inline]
#[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")]
pub const fn as_millis_f32(&self) -> f32 {
(self.secs as f32) * (MILLIS_PER_SEC as f32)
+ (self.nanos.0 as f32) / (NANOS_PER_MILLI as f32)
}

/// Creates a new `Duration` from the specified number of seconds represented
/// as `f64`.
///
Expand Down