1 #![stable(feature = "duration_core", since = "1.25.0")]
3 //! Temporal quantification.
7 //! There are multiple ways to create a new [`Duration`]:
10 //! # use std::time::Duration;
11 //! let five_seconds = Duration::from_secs(5);
12 //! assert_eq!(five_seconds, Duration::from_millis(5_000));
13 //! assert_eq!(five_seconds, Duration::from_micros(5_000_000));
14 //! assert_eq!(five_seconds, Duration::from_nanos(5_000_000_000));
16 //! let ten_seconds = Duration::from_secs(10);
17 //! let seven_nanos = Duration::from_nanos(7);
18 //! let total = ten_seconds + seven_nanos;
19 //! assert_eq!(total, Duration::new(10, 7));
24 use crate::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
26 const NANOS_PER_SEC: u32 = 1_000_000_000;
27 const NANOS_PER_MILLI: u32 = 1_000_000;
28 const NANOS_PER_MICRO: u32 = 1_000;
29 const MILLIS_PER_SEC: u64 = 1_000;
30 const MICROS_PER_SEC: u64 = 1_000_000;
32 /// A `Duration` type to represent a span of time, typically used for system
35 /// Each `Duration` is composed of a whole number of seconds and a fractional part
36 /// represented in nanoseconds. If the underlying system does not support
37 /// nanosecond-level precision, APIs binding a system timeout will typically round up
38 /// the number of nanoseconds.
40 /// [`Duration`]s implement many common traits, including [`Add`], [`Sub`], and other
41 /// [`ops`] traits. It implements [`Default`] by returning a zero-length `Duration`.
43 /// [`ops`]: crate::ops
48 /// use std::time::Duration;
50 /// let five_seconds = Duration::new(5, 0);
51 /// let five_seconds_and_five_nanos = five_seconds + Duration::new(0, 5);
53 /// assert_eq!(five_seconds_and_five_nanos.as_secs(), 5);
54 /// assert_eq!(five_seconds_and_five_nanos.subsec_nanos(), 5);
56 /// let ten_millis = Duration::from_millis(10);
59 /// # Formatting `Duration` values
61 /// `Duration` intentionally does not have a `Display` impl, as there are a
62 /// variety of ways to format spans of time for human readability. `Duration`
63 /// provides a `Debug` impl that shows the full precision of the value.
65 /// The `Debug` output uses the non-ASCII "µs" suffix for microseconds. If your
66 /// program output may appear in contexts that cannot rely on full Unicode
67 /// compatibility, you may wish to format `Duration` objects yourself or use a
69 #[stable(feature = "duration", since = "1.3.0")]
70 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
71 #[cfg_attr(not(test), rustc_diagnostic_item = "Duration")]
74 nanos: u32, // Always 0 <= nanos < NANOS_PER_SEC
78 /// The duration of one second.
83 /// #![feature(duration_constants)]
84 /// use std::time::Duration;
86 /// assert_eq!(Duration::SECOND, Duration::from_secs(1));
88 #[unstable(feature = "duration_constants", issue = "57391")]
89 pub const SECOND: Duration = Duration::from_secs(1);
91 /// The duration of one millisecond.
96 /// #![feature(duration_constants)]
97 /// use std::time::Duration;
99 /// assert_eq!(Duration::MILLISECOND, Duration::from_millis(1));
101 #[unstable(feature = "duration_constants", issue = "57391")]
102 pub const MILLISECOND: Duration = Duration::from_millis(1);
104 /// The duration of one microsecond.
109 /// #![feature(duration_constants)]
110 /// use std::time::Duration;
112 /// assert_eq!(Duration::MICROSECOND, Duration::from_micros(1));
114 #[unstable(feature = "duration_constants", issue = "57391")]
115 pub const MICROSECOND: Duration = Duration::from_micros(1);
117 /// The duration of one nanosecond.
122 /// #![feature(duration_constants)]
123 /// use std::time::Duration;
125 /// assert_eq!(Duration::NANOSECOND, Duration::from_nanos(1));
127 #[unstable(feature = "duration_constants", issue = "57391")]
128 pub const NANOSECOND: Duration = Duration::from_nanos(1);
130 /// A duration of zero time.
135 /// use std::time::Duration;
137 /// let duration = Duration::ZERO;
138 /// assert!(duration.is_zero());
139 /// assert_eq!(duration.as_nanos(), 0);
141 #[stable(feature = "duration_zero", since = "1.53.0")]
142 pub const ZERO: Duration = Duration::from_nanos(0);
144 /// The maximum duration.
146 /// May vary by platform as necessary. Must be able to contain the difference between
147 /// two instances of [`Instant`] or two instances of [`SystemTime`].
148 /// This constraint gives it a value of about 584,942,417,355 years in practice,
149 /// which is currently used on all platforms.
154 /// use std::time::Duration;
156 /// assert_eq!(Duration::MAX, Duration::new(u64::MAX, 1_000_000_000 - 1));
158 /// [`Instant`]: ../../std/time/struct.Instant.html
159 /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
160 #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
161 pub const MAX: Duration = Duration::new(u64::MAX, NANOS_PER_SEC - 1);
163 /// Creates a new `Duration` from the specified number of whole seconds and
164 /// additional nanoseconds.
166 /// If the number of nanoseconds is greater than 1 billion (the number of
167 /// nanoseconds in a second), then it will carry over into the seconds provided.
171 /// This constructor will panic if the carry from the nanoseconds overflows
172 /// the seconds counter.
177 /// use std::time::Duration;
179 /// let five_seconds = Duration::new(5, 0);
181 #[stable(feature = "duration", since = "1.3.0")]
184 #[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
185 pub const fn new(secs: u64, nanos: u32) -> Duration {
186 let secs = match secs.checked_add((nanos / NANOS_PER_SEC) as u64) {
188 None => panic!("overflow in Duration::new"),
190 let nanos = nanos % NANOS_PER_SEC;
191 Duration { secs, nanos }
194 /// Creates a new `Duration` from the specified number of whole seconds.
199 /// use std::time::Duration;
201 /// let duration = Duration::from_secs(5);
203 /// assert_eq!(5, duration.as_secs());
204 /// assert_eq!(0, duration.subsec_nanos());
206 #[stable(feature = "duration", since = "1.3.0")]
209 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
210 pub const fn from_secs(secs: u64) -> Duration {
211 Duration { secs, nanos: 0 }
214 /// Creates a new `Duration` from the specified number of milliseconds.
219 /// use std::time::Duration;
221 /// let duration = Duration::from_millis(2569);
223 /// assert_eq!(2, duration.as_secs());
224 /// assert_eq!(569_000_000, duration.subsec_nanos());
226 #[stable(feature = "duration", since = "1.3.0")]
229 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
230 pub const fn from_millis(millis: u64) -> Duration {
232 secs: millis / MILLIS_PER_SEC,
233 nanos: ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI,
237 /// Creates a new `Duration` from the specified number of microseconds.
242 /// use std::time::Duration;
244 /// let duration = Duration::from_micros(1_000_002);
246 /// assert_eq!(1, duration.as_secs());
247 /// assert_eq!(2000, duration.subsec_nanos());
249 #[stable(feature = "duration_from_micros", since = "1.27.0")]
252 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
253 pub const fn from_micros(micros: u64) -> Duration {
255 secs: micros / MICROS_PER_SEC,
256 nanos: ((micros % MICROS_PER_SEC) as u32) * NANOS_PER_MICRO,
260 /// Creates a new `Duration` from the specified number of nanoseconds.
265 /// use std::time::Duration;
267 /// let duration = Duration::from_nanos(1_000_000_123);
269 /// assert_eq!(1, duration.as_secs());
270 /// assert_eq!(123, duration.subsec_nanos());
272 #[stable(feature = "duration_extras", since = "1.27.0")]
275 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
276 pub const fn from_nanos(nanos: u64) -> Duration {
278 secs: nanos / (NANOS_PER_SEC as u64),
279 nanos: (nanos % (NANOS_PER_SEC as u64)) as u32,
283 /// Returns true if this `Duration` spans no time.
288 /// use std::time::Duration;
290 /// assert!(Duration::ZERO.is_zero());
291 /// assert!(Duration::new(0, 0).is_zero());
292 /// assert!(Duration::from_nanos(0).is_zero());
293 /// assert!(Duration::from_secs(0).is_zero());
295 /// assert!(!Duration::new(1, 1).is_zero());
296 /// assert!(!Duration::from_nanos(1).is_zero());
297 /// assert!(!Duration::from_secs(1).is_zero());
300 #[stable(feature = "duration_zero", since = "1.53.0")]
301 #[rustc_const_stable(feature = "duration_zero", since = "1.53.0")]
303 pub const fn is_zero(&self) -> bool {
304 self.secs == 0 && self.nanos == 0
307 /// Returns the number of _whole_ seconds contained by this `Duration`.
309 /// The returned value does not include the fractional (nanosecond) part of the
310 /// duration, which can be obtained using [`subsec_nanos`].
315 /// use std::time::Duration;
317 /// let duration = Duration::new(5, 730023852);
318 /// assert_eq!(duration.as_secs(), 5);
321 /// To determine the total number of seconds represented by the `Duration`,
322 /// use `as_secs` in combination with [`subsec_nanos`]:
325 /// use std::time::Duration;
327 /// let duration = Duration::new(5, 730023852);
329 /// assert_eq!(5.730023852,
330 /// duration.as_secs() as f64
331 /// + duration.subsec_nanos() as f64 * 1e-9);
334 /// [`subsec_nanos`]: Duration::subsec_nanos
335 #[stable(feature = "duration", since = "1.3.0")]
336 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
339 pub const fn as_secs(&self) -> u64 {
343 /// Returns the fractional part of this `Duration`, in whole milliseconds.
345 /// This method does **not** return the length of the duration when
346 /// represented by milliseconds. The returned number always represents a
347 /// fractional portion of a second (i.e., it is less than one thousand).
352 /// use std::time::Duration;
354 /// let duration = Duration::from_millis(5432);
355 /// assert_eq!(duration.as_secs(), 5);
356 /// assert_eq!(duration.subsec_millis(), 432);
358 #[stable(feature = "duration_extras", since = "1.27.0")]
359 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
362 pub const fn subsec_millis(&self) -> u32 {
363 self.nanos / NANOS_PER_MILLI
366 /// Returns the fractional part of this `Duration`, in whole microseconds.
368 /// This method does **not** return the length of the duration when
369 /// represented by microseconds. The returned number always represents a
370 /// fractional portion of a second (i.e., it is less than one million).
375 /// use std::time::Duration;
377 /// let duration = Duration::from_micros(1_234_567);
378 /// assert_eq!(duration.as_secs(), 1);
379 /// assert_eq!(duration.subsec_micros(), 234_567);
381 #[stable(feature = "duration_extras", since = "1.27.0")]
382 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
385 pub const fn subsec_micros(&self) -> u32 {
386 self.nanos / NANOS_PER_MICRO
389 /// Returns the fractional part of this `Duration`, in nanoseconds.
391 /// This method does **not** return the length of the duration when
392 /// represented by nanoseconds. The returned number always represents a
393 /// fractional portion of a second (i.e., it is less than one billion).
398 /// use std::time::Duration;
400 /// let duration = Duration::from_millis(5010);
401 /// assert_eq!(duration.as_secs(), 5);
402 /// assert_eq!(duration.subsec_nanos(), 10_000_000);
404 #[stable(feature = "duration", since = "1.3.0")]
405 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
408 pub const fn subsec_nanos(&self) -> u32 {
412 /// Returns the total number of whole milliseconds contained by this `Duration`.
417 /// use std::time::Duration;
419 /// let duration = Duration::new(5, 730023852);
420 /// assert_eq!(duration.as_millis(), 5730);
422 #[stable(feature = "duration_as_u128", since = "1.33.0")]
423 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
426 pub const fn as_millis(&self) -> u128 {
427 self.secs as u128 * MILLIS_PER_SEC as u128 + (self.nanos / NANOS_PER_MILLI) as u128
430 /// Returns the total number of whole microseconds contained by this `Duration`.
435 /// use std::time::Duration;
437 /// let duration = Duration::new(5, 730023852);
438 /// assert_eq!(duration.as_micros(), 5730023);
440 #[stable(feature = "duration_as_u128", since = "1.33.0")]
441 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
444 pub const fn as_micros(&self) -> u128 {
445 self.secs as u128 * MICROS_PER_SEC as u128 + (self.nanos / NANOS_PER_MICRO) as u128
448 /// Returns the total number of nanoseconds contained by this `Duration`.
453 /// use std::time::Duration;
455 /// let duration = Duration::new(5, 730023852);
456 /// assert_eq!(duration.as_nanos(), 5730023852);
458 #[stable(feature = "duration_as_u128", since = "1.33.0")]
459 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
462 pub const fn as_nanos(&self) -> u128 {
463 self.secs as u128 * NANOS_PER_SEC as u128 + self.nanos as u128
466 /// Checked `Duration` addition. Computes `self + other`, returning [`None`]
467 /// if overflow occurred.
474 /// use std::time::Duration;
476 /// assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1)));
477 /// assert_eq!(Duration::new(1, 0).checked_add(Duration::new(u64::MAX, 0)), None);
479 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
480 #[must_use = "this returns the result of the operation, \
481 without modifying the original"]
483 #[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
484 pub const fn checked_add(self, rhs: Duration) -> Option<Duration> {
485 if let Some(mut secs) = self.secs.checked_add(rhs.secs) {
486 let mut nanos = self.nanos + rhs.nanos;
487 if nanos >= NANOS_PER_SEC {
488 nanos -= NANOS_PER_SEC;
489 if let Some(new_secs) = secs.checked_add(1) {
495 debug_assert!(nanos < NANOS_PER_SEC);
496 Some(Duration { secs, nanos })
502 /// Saturating `Duration` addition. Computes `self + other`, returning [`Duration::MAX`]
503 /// if overflow occurred.
508 /// #![feature(duration_constants)]
509 /// use std::time::Duration;
511 /// assert_eq!(Duration::new(0, 0).saturating_add(Duration::new(0, 1)), Duration::new(0, 1));
512 /// assert_eq!(Duration::new(1, 0).saturating_add(Duration::new(u64::MAX, 0)), Duration::MAX);
514 #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
515 #[must_use = "this returns the result of the operation, \
516 without modifying the original"]
518 #[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
519 pub const fn saturating_add(self, rhs: Duration) -> Duration {
520 match self.checked_add(rhs) {
522 None => Duration::MAX,
526 /// Checked `Duration` subtraction. Computes `self - other`, returning [`None`]
527 /// if the result would be negative or if overflow occurred.
534 /// use std::time::Duration;
536 /// assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1)));
537 /// assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None);
539 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
540 #[must_use = "this returns the result of the operation, \
541 without modifying the original"]
543 #[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
544 pub const fn checked_sub(self, rhs: Duration) -> Option<Duration> {
545 if let Some(mut secs) = self.secs.checked_sub(rhs.secs) {
546 let nanos = if self.nanos >= rhs.nanos {
547 self.nanos - rhs.nanos
548 } else if let Some(sub_secs) = secs.checked_sub(1) {
550 self.nanos + NANOS_PER_SEC - rhs.nanos
554 debug_assert!(nanos < NANOS_PER_SEC);
555 Some(Duration { secs, nanos })
561 /// Saturating `Duration` subtraction. Computes `self - other`, returning [`Duration::ZERO`]
562 /// if the result would be negative or if overflow occurred.
567 /// use std::time::Duration;
569 /// assert_eq!(Duration::new(0, 1).saturating_sub(Duration::new(0, 0)), Duration::new(0, 1));
570 /// assert_eq!(Duration::new(0, 0).saturating_sub(Duration::new(0, 1)), Duration::ZERO);
572 #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
573 #[must_use = "this returns the result of the operation, \
574 without modifying the original"]
576 #[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
577 pub const fn saturating_sub(self, rhs: Duration) -> Duration {
578 match self.checked_sub(rhs) {
580 None => Duration::ZERO,
584 /// Checked `Duration` multiplication. Computes `self * other`, returning
585 /// [`None`] if overflow occurred.
592 /// use std::time::Duration;
594 /// assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2)));
595 /// assert_eq!(Duration::new(u64::MAX - 1, 0).checked_mul(2), None);
597 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
598 #[must_use = "this returns the result of the operation, \
599 without modifying the original"]
601 #[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
602 pub const fn checked_mul(self, rhs: u32) -> Option<Duration> {
603 // Multiply nanoseconds as u64, because it cannot overflow that way.
604 let total_nanos = self.nanos as u64 * rhs as u64;
605 let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
606 let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
607 if let Some(s) = self.secs.checked_mul(rhs as u64) {
608 if let Some(secs) = s.checked_add(extra_secs) {
609 debug_assert!(nanos < NANOS_PER_SEC);
610 return Some(Duration { secs, nanos });
616 /// Saturating `Duration` multiplication. Computes `self * other`, returning
617 /// [`Duration::MAX`] if overflow occurred.
622 /// #![feature(duration_constants)]
623 /// use std::time::Duration;
625 /// assert_eq!(Duration::new(0, 500_000_001).saturating_mul(2), Duration::new(1, 2));
626 /// assert_eq!(Duration::new(u64::MAX - 1, 0).saturating_mul(2), Duration::MAX);
628 #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
629 #[must_use = "this returns the result of the operation, \
630 without modifying the original"]
632 #[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
633 pub const fn saturating_mul(self, rhs: u32) -> Duration {
634 match self.checked_mul(rhs) {
636 None => Duration::MAX,
640 /// Checked `Duration` division. Computes `self / other`, returning [`None`]
648 /// use std::time::Duration;
650 /// assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
651 /// assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
652 /// assert_eq!(Duration::new(2, 0).checked_div(0), None);
654 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
655 #[must_use = "this returns the result of the operation, \
656 without modifying the original"]
658 #[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
659 pub const fn checked_div(self, rhs: u32) -> Option<Duration> {
661 let secs = self.secs / (rhs as u64);
662 let carry = self.secs - secs * (rhs as u64);
663 let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64);
664 let nanos = self.nanos / rhs + (extra_nanos as u32);
665 debug_assert!(nanos < NANOS_PER_SEC);
666 Some(Duration { secs, nanos })
672 /// Returns the number of seconds contained by this `Duration` as `f64`.
674 /// The returned value does include the fractional (nanosecond) part of the duration.
678 /// use std::time::Duration;
680 /// let dur = Duration::new(2, 700_000_000);
681 /// assert_eq!(dur.as_secs_f64(), 2.7);
683 #[stable(feature = "duration_float", since = "1.38.0")]
686 #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")]
687 pub const fn as_secs_f64(&self) -> f64 {
688 (self.secs as f64) + (self.nanos as f64) / (NANOS_PER_SEC as f64)
691 /// Returns the number of seconds contained by this `Duration` as `f32`.
693 /// The returned value does include the fractional (nanosecond) part of the duration.
697 /// use std::time::Duration;
699 /// let dur = Duration::new(2, 700_000_000);
700 /// assert_eq!(dur.as_secs_f32(), 2.7);
702 #[stable(feature = "duration_float", since = "1.38.0")]
705 #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")]
706 pub const fn as_secs_f32(&self) -> f32 {
707 (self.secs as f32) + (self.nanos as f32) / (NANOS_PER_SEC as f32)
710 /// Creates a new `Duration` from the specified number of seconds represented
714 /// This constructor will panic if `secs` is negative, overflows `Duration` or not finite.
718 /// use std::time::Duration;
720 /// let res = Duration::from_secs_f64(0.0);
721 /// assert_eq!(res, Duration::new(0, 0));
722 /// let res = Duration::from_secs_f64(1e-20);
723 /// assert_eq!(res, Duration::new(0, 0));
724 /// let res = Duration::from_secs_f64(4.2e-7);
725 /// assert_eq!(res, Duration::new(0, 420));
726 /// let res = Duration::from_secs_f64(2.7);
727 /// assert_eq!(res, Duration::new(2, 700_000_000));
728 /// let res = Duration::from_secs_f64(3e10);
729 /// assert_eq!(res, Duration::new(30_000_000_000, 0));
730 /// // subnormal float
731 /// let res = Duration::from_secs_f64(f64::from_bits(1));
732 /// assert_eq!(res, Duration::new(0, 0));
733 /// // conversion uses rounding
734 /// let res = Duration::from_secs_f64(0.999e-9);
735 /// assert_eq!(res, Duration::new(0, 1));
737 #[stable(feature = "duration_float", since = "1.38.0")]
740 #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")]
741 pub const fn from_secs_f64(secs: f64) -> Duration {
742 match Duration::try_from_secs_f64(secs) {
744 Err(e) => panic!("{}", e.description()),
748 /// Creates a new `Duration` from the specified number of seconds represented
752 /// This constructor will panic if `secs` is negative, overflows `Duration` or not finite.
756 /// use std::time::Duration;
758 /// let res = Duration::from_secs_f32(0.0);
759 /// assert_eq!(res, Duration::new(0, 0));
760 /// let res = Duration::from_secs_f32(1e-20);
761 /// assert_eq!(res, Duration::new(0, 0));
762 /// let res = Duration::from_secs_f32(4.2e-7);
763 /// assert_eq!(res, Duration::new(0, 420));
764 /// let res = Duration::from_secs_f32(2.7);
765 /// assert_eq!(res, Duration::new(2, 700_000_048));
766 /// let res = Duration::from_secs_f32(3e10);
767 /// assert_eq!(res, Duration::new(30_000_001_024, 0));
768 /// // subnormal float
769 /// let res = Duration::from_secs_f32(f32::from_bits(1));
770 /// assert_eq!(res, Duration::new(0, 0));
771 /// // conversion uses rounding
772 /// let res = Duration::from_secs_f32(0.999e-9);
773 /// assert_eq!(res, Duration::new(0, 1));
775 #[stable(feature = "duration_float", since = "1.38.0")]
778 #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")]
779 pub const fn from_secs_f32(secs: f32) -> Duration {
780 match Duration::try_from_secs_f32(secs) {
782 Err(e) => panic!("{}", e.description()),
786 /// Multiplies `Duration` by `f64`.
789 /// This method will panic if result is negative, overflows `Duration` or not finite.
793 /// use std::time::Duration;
795 /// let dur = Duration::new(2, 700_000_000);
796 /// assert_eq!(dur.mul_f64(3.14), Duration::new(8, 478_000_000));
797 /// assert_eq!(dur.mul_f64(3.14e5), Duration::new(847_800, 0));
799 #[stable(feature = "duration_float", since = "1.38.0")]
800 #[must_use = "this returns the result of the operation, \
801 without modifying the original"]
803 #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")]
804 pub const fn mul_f64(self, rhs: f64) -> Duration {
805 Duration::from_secs_f64(rhs * self.as_secs_f64())
808 /// Multiplies `Duration` by `f32`.
811 /// This method will panic if result is negative, overflows `Duration` or not finite.
815 /// use std::time::Duration;
817 /// let dur = Duration::new(2, 700_000_000);
818 /// assert_eq!(dur.mul_f32(3.14), Duration::new(8, 478_000_641));
819 /// assert_eq!(dur.mul_f32(3.14e5), Duration::new(847800, 0));
821 #[stable(feature = "duration_float", since = "1.38.0")]
822 #[must_use = "this returns the result of the operation, \
823 without modifying the original"]
825 #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")]
826 pub const fn mul_f32(self, rhs: f32) -> Duration {
827 Duration::from_secs_f32(rhs * self.as_secs_f32())
830 /// Divide `Duration` by `f64`.
833 /// This method will panic if result is negative, overflows `Duration` or not finite.
837 /// use std::time::Duration;
839 /// let dur = Duration::new(2, 700_000_000);
840 /// assert_eq!(dur.div_f64(3.14), Duration::new(0, 859_872_611));
841 /// assert_eq!(dur.div_f64(3.14e5), Duration::new(0, 8_599));
843 #[stable(feature = "duration_float", since = "1.38.0")]
844 #[must_use = "this returns the result of the operation, \
845 without modifying the original"]
847 #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")]
848 pub const fn div_f64(self, rhs: f64) -> Duration {
849 Duration::from_secs_f64(self.as_secs_f64() / rhs)
852 /// Divide `Duration` by `f32`.
855 /// This method will panic if result is negative, overflows `Duration` or not finite.
859 /// use std::time::Duration;
861 /// let dur = Duration::new(2, 700_000_000);
862 /// // note that due to rounding errors result is slightly
863 /// // different from 0.859_872_611
864 /// assert_eq!(dur.div_f32(3.14), Duration::new(0, 859_872_580));
865 /// assert_eq!(dur.div_f32(3.14e5), Duration::new(0, 8_599));
867 #[stable(feature = "duration_float", since = "1.38.0")]
868 #[must_use = "this returns the result of the operation, \
869 without modifying the original"]
871 #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")]
872 pub const fn div_f32(self, rhs: f32) -> Duration {
873 Duration::from_secs_f32(self.as_secs_f32() / rhs)
876 /// Divide `Duration` by `Duration` and return `f64`.
880 /// #![feature(div_duration)]
881 /// use std::time::Duration;
883 /// let dur1 = Duration::new(2, 700_000_000);
884 /// let dur2 = Duration::new(5, 400_000_000);
885 /// assert_eq!(dur1.div_duration_f64(dur2), 0.5);
887 #[unstable(feature = "div_duration", issue = "63139")]
888 #[must_use = "this returns the result of the operation, \
889 without modifying the original"]
891 #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")]
892 pub const fn div_duration_f64(self, rhs: Duration) -> f64 {
893 self.as_secs_f64() / rhs.as_secs_f64()
896 /// Divide `Duration` by `Duration` and return `f32`.
900 /// #![feature(div_duration)]
901 /// use std::time::Duration;
903 /// let dur1 = Duration::new(2, 700_000_000);
904 /// let dur2 = Duration::new(5, 400_000_000);
905 /// assert_eq!(dur1.div_duration_f32(dur2), 0.5);
907 #[unstable(feature = "div_duration", issue = "63139")]
908 #[must_use = "this returns the result of the operation, \
909 without modifying the original"]
911 #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")]
912 pub const fn div_duration_f32(self, rhs: Duration) -> f32 {
913 self.as_secs_f32() / rhs.as_secs_f32()
917 #[stable(feature = "duration", since = "1.3.0")]
918 impl Add for Duration {
919 type Output = Duration;
921 fn add(self, rhs: Duration) -> Duration {
922 self.checked_add(rhs).expect("overflow when adding durations")
926 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
927 impl AddAssign for Duration {
928 fn add_assign(&mut self, rhs: Duration) {
933 #[stable(feature = "duration", since = "1.3.0")]
934 impl Sub for Duration {
935 type Output = Duration;
937 fn sub(self, rhs: Duration) -> Duration {
938 self.checked_sub(rhs).expect("overflow when subtracting durations")
942 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
943 impl SubAssign for Duration {
944 fn sub_assign(&mut self, rhs: Duration) {
949 #[stable(feature = "duration", since = "1.3.0")]
950 impl Mul<u32> for Duration {
951 type Output = Duration;
953 fn mul(self, rhs: u32) -> Duration {
954 self.checked_mul(rhs).expect("overflow when multiplying duration by scalar")
958 #[stable(feature = "symmetric_u32_duration_mul", since = "1.31.0")]
959 impl Mul<Duration> for u32 {
960 type Output = Duration;
962 fn mul(self, rhs: Duration) -> Duration {
967 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
968 impl MulAssign<u32> for Duration {
969 fn mul_assign(&mut self, rhs: u32) {
974 #[stable(feature = "duration", since = "1.3.0")]
975 impl Div<u32> for Duration {
976 type Output = Duration;
978 fn div(self, rhs: u32) -> Duration {
979 self.checked_div(rhs).expect("divide by zero error when dividing duration by scalar")
983 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
984 impl DivAssign<u32> for Duration {
985 fn div_assign(&mut self, rhs: u32) {
990 macro_rules! sum_durations {
992 let mut total_secs: u64 = 0;
993 let mut total_nanos: u64 = 0;
997 total_secs.checked_add(entry.secs).expect("overflow in iter::sum over durations");
998 total_nanos = match total_nanos.checked_add(entry.nanos as u64) {
1001 total_secs = total_secs
1002 .checked_add(total_nanos / NANOS_PER_SEC as u64)
1003 .expect("overflow in iter::sum over durations");
1004 (total_nanos % NANOS_PER_SEC as u64) + entry.nanos as u64
1008 total_secs = total_secs
1009 .checked_add(total_nanos / NANOS_PER_SEC as u64)
1010 .expect("overflow in iter::sum over durations");
1011 total_nanos = total_nanos % NANOS_PER_SEC as u64;
1012 Duration { secs: total_secs, nanos: total_nanos as u32 }
1016 #[stable(feature = "duration_sum", since = "1.16.0")]
1017 impl Sum for Duration {
1018 fn sum<I: Iterator<Item = Duration>>(iter: I) -> Duration {
1019 sum_durations!(iter)
1023 #[stable(feature = "duration_sum", since = "1.16.0")]
1024 impl<'a> Sum<&'a Duration> for Duration {
1025 fn sum<I: Iterator<Item = &'a Duration>>(iter: I) -> Duration {
1026 sum_durations!(iter)
1030 #[stable(feature = "duration_debug_impl", since = "1.27.0")]
1031 impl fmt::Debug for Duration {
1032 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1033 /// Formats a floating point number in decimal notation.
1035 /// The number is given as the `integer_part` and a fractional part.
1036 /// The value of the fractional part is `fractional_part / divisor`. So
1037 /// `integer_part` = 3, `fractional_part` = 12 and `divisor` = 100
1038 /// represents the number `3.012`. Trailing zeros are omitted.
1040 /// `divisor` must not be above 100_000_000. It also should be a power
1041 /// of 10, everything else doesn't make sense. `fractional_part` has
1042 /// to be less than `10 * divisor`!
1044 /// A prefix and postfix may be added. The whole thing is padded
1045 /// to the formatter's `width`, if specified.
1047 f: &mut fmt::Formatter<'_>,
1048 mut integer_part: u64,
1049 mut fractional_part: u32,
1054 // Encode the fractional part into a temporary buffer. The buffer
1055 // only need to hold 9 elements, because `fractional_part` has to
1056 // be smaller than 10^9. The buffer is prefilled with '0' digits
1057 // to simplify the code below.
1058 let mut buf = [b'0'; 9];
1060 // The next digit is written at this position
1063 // We keep writing digits into the buffer while there are non-zero
1064 // digits left and we haven't written enough digits yet.
1065 while fractional_part > 0 && pos < f.precision().unwrap_or(9) {
1066 // Write new digit into the buffer
1067 buf[pos] = b'0' + (fractional_part / divisor) as u8;
1069 fractional_part %= divisor;
1074 // If a precision < 9 was specified, there may be some non-zero
1075 // digits left that weren't written into the buffer. In that case we
1076 // need to perform rounding to match the semantics of printing
1077 // normal floating point numbers. However, we only need to do work
1078 // when rounding up. This happens if the first digit of the
1079 // remaining ones is >= 5.
1080 if fractional_part > 0 && fractional_part >= divisor * 5 {
1081 // Round up the number contained in the buffer. We go through
1082 // the buffer backwards and keep track of the carry.
1083 let mut rev_pos = pos;
1084 let mut carry = true;
1085 while carry && rev_pos > 0 {
1088 // If the digit in the buffer is not '9', we just need to
1089 // increment it and can stop then (since we don't have a
1090 // carry anymore). Otherwise, we set it to '0' (overflow)
1092 if buf[rev_pos] < b'9' {
1096 buf[rev_pos] = b'0';
1100 // If we still have the carry bit set, that means that we set
1101 // the whole buffer to '0's and need to increment the integer
1108 // Determine the end of the buffer: if precision is set, we just
1109 // use as many digits from the buffer (capped to 9). If it isn't
1110 // set, we only use all digits up to the last non-zero one.
1111 let end = f.precision().map(|p| crate::cmp::min(p, 9)).unwrap_or(pos);
1113 // This closure emits the formatted duration without emitting any
1114 // padding (padding is calculated below).
1115 let emit_without_padding = |f: &mut fmt::Formatter<'_>| {
1116 write!(f, "{}{}", prefix, integer_part)?;
1118 // Write the decimal point and the fractional part (if any).
1120 // SAFETY: We are only writing ASCII digits into the buffer and
1121 // it was initialized with '0's, so it contains valid UTF8.
1122 let s = unsafe { crate::str::from_utf8_unchecked(&buf[..end]) };
1124 // If the user request a precision > 9, we pad '0's at the end.
1125 let w = f.precision().unwrap_or(pos);
1126 write!(f, ".{:0<width$}", s, width = w)?;
1129 write!(f, "{}", postfix)
1134 // No `width` specified. There's no need to calculate the
1135 // length of the output in this case, just emit it.
1136 emit_without_padding(f)
1138 Some(requested_w) => {
1139 // A `width` was specified. Calculate the actual width of
1140 // the output in order to calculate the required padding.
1141 // It consists of 4 parts:
1142 // 1. The prefix: is either "+" or "", so we can just use len().
1143 // 2. The postfix: can be "µs" so we have to count UTF8 characters.
1144 let mut actual_w = prefix.len() + postfix.chars().count();
1145 // 3. The integer part:
1146 if let Some(log) = integer_part.checked_log10() {
1147 // integer_part is > 0, so has length log10(x)+1
1148 actual_w += 1 + log as usize;
1150 // integer_part is 0, so has length 1.
1153 // 4. The fractional part (if any):
1155 let frac_part_w = f.precision().unwrap_or(pos);
1156 actual_w += 1 + frac_part_w;
1159 if requested_w <= actual_w {
1160 // Output is already longer than `width`, so don't pad.
1161 emit_without_padding(f)
1163 // We need to add padding. Use the `Formatter::padding` helper function.
1164 let default_align = crate::fmt::rt::v1::Alignment::Left;
1165 let post_padding = f.padding(requested_w - actual_w, default_align)?;
1166 emit_without_padding(f)?;
1167 post_padding.write(f)
1173 // Print leading '+' sign if requested
1174 let prefix = if f.sign_plus() { "+" } else { "" };
1177 fmt_decimal(f, self.secs, self.nanos, NANOS_PER_SEC / 10, prefix, "s")
1178 } else if self.nanos >= NANOS_PER_MILLI {
1181 (self.nanos / NANOS_PER_MILLI) as u64,
1182 self.nanos % NANOS_PER_MILLI,
1183 NANOS_PER_MILLI / 10,
1187 } else if self.nanos >= NANOS_PER_MICRO {
1190 (self.nanos / NANOS_PER_MICRO) as u64,
1191 self.nanos % NANOS_PER_MICRO,
1192 NANOS_PER_MICRO / 10,
1197 fmt_decimal(f, self.nanos as u64, 0, 1, prefix, "ns")
1202 /// An error which can be returned when converting a floating-point value of seconds
1203 /// into a [`Duration`].
1205 /// This error is used as the error type for [`Duration::try_from_secs_f32`] and
1206 /// [`Duration::try_from_secs_f64`].
1211 /// #![feature(duration_checked_float)]
1212 /// use std::time::Duration;
1214 /// if let Err(e) = Duration::try_from_secs_f32(-1.0) {
1215 /// println!("Failed conversion to Duration: {e}");
1218 #[derive(Debug, Clone, PartialEq, Eq)]
1219 #[unstable(feature = "duration_checked_float", issue = "83400")]
1220 pub struct FromFloatSecsError {
1221 kind: FromFloatSecsErrorKind,
1224 impl FromFloatSecsError {
1225 const fn description(&self) -> &'static str {
1227 FromFloatSecsErrorKind::Negative => {
1228 "can not convert float seconds to Duration: value is negative"
1230 FromFloatSecsErrorKind::OverflowOrNan => {
1231 "can not convert float seconds to Duration: value is either too big or NaN"
1237 #[unstable(feature = "duration_checked_float", issue = "83400")]
1238 impl fmt::Display for FromFloatSecsError {
1239 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1240 self.description().fmt(f)
1244 #[derive(Debug, Clone, PartialEq, Eq)]
1245 enum FromFloatSecsErrorKind {
1246 // Value is negative.
1248 // Value is either too big to be represented as `Duration` or `NaN`.
1252 macro_rules! try_from_secs {
1255 mantissa_bits = $mant_bits: literal,
1256 exponent_bits = $exp_bits: literal,
1257 offset = $offset: literal,
1258 bits_ty = $bits_ty:ty,
1259 double_ty = $double_ty:ty,
1261 const MIN_EXP: i16 = 1 - (1i16 << $exp_bits) / 2;
1262 const MANT_MASK: $bits_ty = (1 << $mant_bits) - 1;
1263 const EXP_MASK: $bits_ty = (1 << $exp_bits) - 1;
1265 if $secs.is_sign_negative() {
1266 return Err(FromFloatSecsError { kind: FromFloatSecsErrorKind::Negative });
1269 let bits = $secs.to_bits();
1270 let mant = (bits & MANT_MASK) | (MANT_MASK + 1);
1271 let exp = ((bits >> $mant_bits) & EXP_MASK) as i16 + MIN_EXP;
1273 let (secs, nanos) = if exp < -31 {
1274 // the input represents less than 1ns and can not be rounded to it
1277 // the input is less than 1 second
1278 let t = <$double_ty>::from(mant) << ($offset + exp);
1279 let nanos_offset = $mant_bits + $offset;
1280 let nanos_tmp = u128::from(NANOS_PER_SEC) * u128::from(t);
1281 let nanos = (nanos_tmp >> nanos_offset) as u32;
1283 let rem_mask = (1 << nanos_offset) - 1;
1284 let rem_msb_mask = 1 << (nanos_offset - 1);
1285 let rem = nanos_tmp & rem_mask;
1286 let is_tie = rem == rem_msb_mask;
1287 let is_even = (nanos & 1) == 0;
1288 let rem_msb = nanos_tmp & rem_msb_mask == 0;
1289 let add_ns = !(rem_msb || (is_even && is_tie));
1291 // f32 does not have enough presicion to trigger the second branch
1292 // since it can not represent numbers between 0.999_999_940_395 and 1.0.
1293 let nanos = nanos + add_ns as u32;
1294 if ($mant_bits == 23) || (nanos != NANOS_PER_SEC) { (0, nanos) } else { (1, 0) }
1295 } else if exp < $mant_bits {
1296 let secs = u64::from(mant >> ($mant_bits - exp));
1297 let t = <$double_ty>::from((mant << exp) & MANT_MASK);
1298 let nanos_offset = $mant_bits;
1299 let nanos_tmp = <$double_ty>::from(NANOS_PER_SEC) * t;
1300 let nanos = (nanos_tmp >> nanos_offset) as u32;
1302 let rem_mask = (1 << nanos_offset) - 1;
1303 let rem_msb_mask = 1 << (nanos_offset - 1);
1304 let rem = nanos_tmp & rem_mask;
1305 let is_tie = rem == rem_msb_mask;
1306 let is_even = (nanos & 1) == 0;
1307 let rem_msb = nanos_tmp & rem_msb_mask == 0;
1308 let add_ns = !(rem_msb || (is_even && is_tie));
1310 // f32 does not have enough presicion to trigger the second branch.
1311 // For example, it can not represent numbers between 1.999_999_880...
1312 // and 2.0. Bigger values result in even smaller presicion of the
1314 let nanos = nanos + add_ns as u32;
1315 if ($mant_bits == 23) || (nanos != NANOS_PER_SEC) {
1320 } else if exp < 64 {
1321 // the input has no fractional part
1322 let secs = u64::from(mant) << (exp - $mant_bits);
1325 return Err(FromFloatSecsError { kind: FromFloatSecsErrorKind::OverflowOrNan });
1328 Ok(Duration { secs, nanos })
1333 /// The checked version of [`from_secs_f32`].
1335 /// [`from_secs_f32`]: Duration::from_secs_f32
1337 /// This constructor will return an `Err` if `secs` is negative, overflows `Duration` or not finite.
1341 /// #![feature(duration_checked_float)]
1343 /// use std::time::Duration;
1345 /// let res = Duration::try_from_secs_f32(0.0);
1346 /// assert_eq!(res, Ok(Duration::new(0, 0)));
1347 /// let res = Duration::try_from_secs_f32(1e-20);
1348 /// assert_eq!(res, Ok(Duration::new(0, 0)));
1349 /// let res = Duration::try_from_secs_f32(4.2e-7);
1350 /// assert_eq!(res, Ok(Duration::new(0, 420)));
1351 /// let res = Duration::try_from_secs_f32(2.7);
1352 /// assert_eq!(res, Ok(Duration::new(2, 700_000_048)));
1353 /// let res = Duration::try_from_secs_f32(3e10);
1354 /// assert_eq!(res, Ok(Duration::new(30_000_001_024, 0)));
1355 /// // subnormal float:
1356 /// let res = Duration::try_from_secs_f32(f32::from_bits(1));
1357 /// assert_eq!(res, Ok(Duration::new(0, 0)));
1359 /// let res = Duration::try_from_secs_f32(-5.0);
1360 /// assert!(res.is_err());
1361 /// let res = Duration::try_from_secs_f32(f32::NAN);
1362 /// assert!(res.is_err());
1363 /// let res = Duration::try_from_secs_f32(2e19);
1364 /// assert!(res.is_err());
1366 /// // the conversion uses rounding with tie resolution to even
1367 /// let res = Duration::try_from_secs_f32(0.999e-9);
1368 /// assert_eq!(res, Ok(Duration::new(0, 1)));
1370 /// // this float represents exactly 976562.5e-9
1371 /// let val = f32::from_bits(0x3A80_0000);
1372 /// let res = Duration::try_from_secs_f32(val);
1373 /// assert_eq!(res, Ok(Duration::new(0, 976_562)));
1375 /// // this float represents exactly 2929687.5e-9
1376 /// let val = f32::from_bits(0x3B40_0000);
1377 /// let res = Duration::try_from_secs_f32(val);
1378 /// assert_eq!(res, Ok(Duration::new(0, 2_929_688)));
1380 /// // this float represents exactly 1.000_976_562_5
1381 /// let val = f32::from_bits(0x3F802000);
1382 /// let res = Duration::try_from_secs_f32(val);
1383 /// assert_eq!(res, Ok(Duration::new(1, 976_562)));
1385 /// // this float represents exactly 1.002_929_687_5
1386 /// let val = f32::from_bits(0x3F806000);
1387 /// let res = Duration::try_from_secs_f32(val);
1388 /// assert_eq!(res, Ok(Duration::new(1, 2_929_688)));
1390 #[unstable(feature = "duration_checked_float", issue = "83400")]
1392 pub const fn try_from_secs_f32(secs: f32) -> Result<Duration, FromFloatSecsError> {
1403 /// The checked version of [`from_secs_f64`].
1405 /// [`from_secs_f64`]: Duration::from_secs_f64
1407 /// This constructor will return an `Err` if `secs` is negative, overflows `Duration` or not finite.
1411 /// #![feature(duration_checked_float)]
1413 /// use std::time::Duration;
1415 /// let res = Duration::try_from_secs_f64(0.0);
1416 /// assert_eq!(res, Ok(Duration::new(0, 0)));
1417 /// let res = Duration::try_from_secs_f64(1e-20);
1418 /// assert_eq!(res, Ok(Duration::new(0, 0)));
1419 /// let res = Duration::try_from_secs_f64(4.2e-7);
1420 /// assert_eq!(res, Ok(Duration::new(0, 420)));
1421 /// let res = Duration::try_from_secs_f64(2.7);
1422 /// assert_eq!(res, Ok(Duration::new(2, 700_000_000)));
1423 /// let res = Duration::try_from_secs_f64(3e10);
1424 /// assert_eq!(res, Ok(Duration::new(30_000_000_000, 0)));
1425 /// // subnormal float
1426 /// let res = Duration::try_from_secs_f64(f64::from_bits(1));
1427 /// assert_eq!(res, Ok(Duration::new(0, 0)));
1429 /// let res = Duration::try_from_secs_f64(-5.0);
1430 /// assert!(res.is_err());
1431 /// let res = Duration::try_from_secs_f64(f64::NAN);
1432 /// assert!(res.is_err());
1433 /// let res = Duration::try_from_secs_f64(2e19);
1434 /// assert!(res.is_err());
1436 /// // the conversion uses rounding with tie resolution to even
1437 /// let res = Duration::try_from_secs_f64(0.999e-9);
1438 /// assert_eq!(res, Ok(Duration::new(0, 1)));
1439 /// let res = Duration::try_from_secs_f64(0.999_999_999_499);
1440 /// assert_eq!(res, Ok(Duration::new(0, 999_999_999)));
1441 /// let res = Duration::try_from_secs_f64(0.999_999_999_501);
1442 /// assert_eq!(res, Ok(Duration::new(1, 0)));
1443 /// let res = Duration::try_from_secs_f64(42.999_999_999_499);
1444 /// assert_eq!(res, Ok(Duration::new(42, 999_999_999)));
1445 /// let res = Duration::try_from_secs_f64(42.999_999_999_501);
1446 /// assert_eq!(res, Ok(Duration::new(43, 0)));
1448 /// // this float represents exactly 976562.5e-9
1449 /// let val = f64::from_bits(0x3F50_0000_0000_0000);
1450 /// let res = Duration::try_from_secs_f64(val);
1451 /// assert_eq!(res, Ok(Duration::new(0, 976_562)));
1453 /// // this float represents exactly 2929687.5e-9
1454 /// let val = f64::from_bits(0x3F68_0000_0000_0000);
1455 /// let res = Duration::try_from_secs_f64(val);
1456 /// assert_eq!(res, Ok(Duration::new(0, 2_929_688)));
1458 /// // this float represents exactly 1.000_976_562_5
1459 /// let val = f64::from_bits(0x3FF0_0400_0000_0000);
1460 /// let res = Duration::try_from_secs_f64(val);
1461 /// assert_eq!(res, Ok(Duration::new(1, 976_562)));
1463 /// // this float represents exactly 1.002_929_687_5
1464 /// let val = f64::from_bits(0x3_FF00_C000_0000_000);
1465 /// let res = Duration::try_from_secs_f64(val);
1466 /// assert_eq!(res, Ok(Duration::new(1, 2_929_688)));
1468 #[unstable(feature = "duration_checked_float", issue = "83400")]
1470 pub const fn try_from_secs_f64(secs: f64) -> Result<Duration, FromFloatSecsError> {