1 #![stable(feature = "duration_core", since = "1.25.0")]
3 //! Temporal quantification.
8 //! use std::time::Duration;
10 //! let five_seconds = Duration::new(5, 0);
11 //! // both declarations are equivalent
12 //! assert_eq!(Duration::new(5, 0), Duration::from_secs(5));
17 use ops::{Add, Sub, Mul, Div, AddAssign, SubAssign, MulAssign, DivAssign};
19 const NANOS_PER_SEC: u32 = 1_000_000_000;
20 const NANOS_PER_MILLI: u32 = 1_000_000;
21 const NANOS_PER_MICRO: u32 = 1_000;
22 const MILLIS_PER_SEC: u64 = 1_000;
23 const MICROS_PER_SEC: u64 = 1_000_000;
24 const MAX_NANOS_F64: f64 = ((u64::MAX as u128 + 1)*(NANOS_PER_SEC as u128)) as f64;
26 /// A `Duration` type to represent a span of time, typically used for system
29 /// Each `Duration` is composed of a whole number of seconds and a fractional part
30 /// represented in nanoseconds. If the underlying system does not support
31 /// nanosecond-level precision, APIs binding a system timeout will typically round up
32 /// the number of nanoseconds.
34 /// `Duration`s implement many common traits, including [`Add`], [`Sub`], and other
37 /// [`Add`]: ../../std/ops/trait.Add.html
38 /// [`Sub`]: ../../std/ops/trait.Sub.html
39 /// [`ops`]: ../../std/ops/index.html
44 /// use std::time::Duration;
46 /// let five_seconds = Duration::new(5, 0);
47 /// let five_seconds_and_five_nanos = five_seconds + Duration::new(0, 5);
49 /// assert_eq!(five_seconds_and_five_nanos.as_secs(), 5);
50 /// assert_eq!(five_seconds_and_five_nanos.subsec_nanos(), 5);
52 /// let ten_millis = Duration::from_millis(10);
54 #[stable(feature = "duration", since = "1.3.0")]
55 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
58 nanos: u32, // Always 0 <= nanos < NANOS_PER_SEC
62 /// Creates a new `Duration` from the specified number of whole seconds and
63 /// additional nanoseconds.
65 /// If the number of nanoseconds is greater than 1 billion (the number of
66 /// nanoseconds in a second), then it will carry over into the seconds provided.
70 /// This constructor will panic if the carry from the nanoseconds overflows
71 /// the seconds counter.
76 /// use std::time::Duration;
78 /// let five_seconds = Duration::new(5, 0);
80 #[stable(feature = "duration", since = "1.3.0")]
82 pub fn new(secs: u64, nanos: u32) -> Duration {
83 let secs = secs.checked_add((nanos / NANOS_PER_SEC) as u64)
84 .expect("overflow in Duration::new");
85 let nanos = nanos % NANOS_PER_SEC;
86 Duration { secs, nanos }
89 /// Creates a new `Duration` from the specified number of whole seconds.
94 /// use std::time::Duration;
96 /// let duration = Duration::from_secs(5);
98 /// assert_eq!(5, duration.as_secs());
99 /// assert_eq!(0, duration.subsec_nanos());
101 #[stable(feature = "duration", since = "1.3.0")]
104 pub const fn from_secs(secs: u64) -> Duration {
105 Duration { secs, nanos: 0 }
108 /// Creates a new `Duration` from the specified number of milliseconds.
113 /// use std::time::Duration;
115 /// let duration = Duration::from_millis(2569);
117 /// assert_eq!(2, duration.as_secs());
118 /// assert_eq!(569_000_000, duration.subsec_nanos());
120 #[stable(feature = "duration", since = "1.3.0")]
123 pub const fn from_millis(millis: u64) -> Duration {
125 secs: millis / MILLIS_PER_SEC,
126 nanos: ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI,
130 /// Creates a new `Duration` from the specified number of microseconds.
135 /// use std::time::Duration;
137 /// let duration = Duration::from_micros(1_000_002);
139 /// assert_eq!(1, duration.as_secs());
140 /// assert_eq!(2000, duration.subsec_nanos());
142 #[stable(feature = "duration_from_micros", since = "1.27.0")]
145 pub const fn from_micros(micros: u64) -> Duration {
147 secs: micros / MICROS_PER_SEC,
148 nanos: ((micros % MICROS_PER_SEC) as u32) * NANOS_PER_MICRO,
152 /// Creates a new `Duration` from the specified number of nanoseconds.
157 /// use std::time::Duration;
159 /// let duration = Duration::from_nanos(1_000_000_123);
161 /// assert_eq!(1, duration.as_secs());
162 /// assert_eq!(123, duration.subsec_nanos());
164 #[stable(feature = "duration_extras", since = "1.27.0")]
167 pub const fn from_nanos(nanos: u64) -> Duration {
169 secs: nanos / (NANOS_PER_SEC as u64),
170 nanos: (nanos % (NANOS_PER_SEC as u64)) as u32,
174 /// Returns the number of _whole_ seconds contained by this `Duration`.
176 /// The returned value does not include the fractional (nanosecond) part of the
177 /// duration, which can be obtained using [`subsec_nanos`].
182 /// use std::time::Duration;
184 /// let duration = Duration::new(5, 730023852);
185 /// assert_eq!(duration.as_secs(), 5);
188 /// To determine the total number of seconds represented by the `Duration`,
189 /// use `as_secs` in combination with [`subsec_nanos`]:
192 /// use std::time::Duration;
194 /// let duration = Duration::new(5, 730023852);
196 /// assert_eq!(5.730023852,
197 /// duration.as_secs() as f64
198 /// + duration.subsec_nanos() as f64 * 1e-9);
201 /// [`subsec_nanos`]: #method.subsec_nanos
202 #[stable(feature = "duration", since = "1.3.0")]
204 pub const fn as_secs(&self) -> u64 { self.secs }
206 /// Returns the fractional part of this `Duration`, in whole milliseconds.
208 /// This method does **not** return the length of the duration when
209 /// represented by milliseconds. The returned number always represents a
210 /// fractional portion of a second (i.e., it is less than one thousand).
215 /// use std::time::Duration;
217 /// let duration = Duration::from_millis(5432);
218 /// assert_eq!(duration.as_secs(), 5);
219 /// assert_eq!(duration.subsec_millis(), 432);
221 #[stable(feature = "duration_extras", since = "1.27.0")]
223 pub const fn subsec_millis(&self) -> u32 { self.nanos / NANOS_PER_MILLI }
225 /// Returns the fractional part of this `Duration`, in whole microseconds.
227 /// This method does **not** return the length of the duration when
228 /// represented by microseconds. The returned number always represents a
229 /// fractional portion of a second (i.e., it is less than one million).
234 /// use std::time::Duration;
236 /// let duration = Duration::from_micros(1_234_567);
237 /// assert_eq!(duration.as_secs(), 1);
238 /// assert_eq!(duration.subsec_micros(), 234_567);
240 #[stable(feature = "duration_extras", since = "1.27.0")]
242 pub const fn subsec_micros(&self) -> u32 { self.nanos / NANOS_PER_MICRO }
244 /// Returns the fractional part of this `Duration`, in nanoseconds.
246 /// This method does **not** return the length of the duration when
247 /// represented by nanoseconds. The returned number always represents a
248 /// fractional portion of a second (i.e., it is less than one billion).
253 /// use std::time::Duration;
255 /// let duration = Duration::from_millis(5010);
256 /// assert_eq!(duration.as_secs(), 5);
257 /// assert_eq!(duration.subsec_nanos(), 10_000_000);
259 #[stable(feature = "duration", since = "1.3.0")]
261 pub const fn subsec_nanos(&self) -> u32 { self.nanos }
263 /// Returns the total number of whole milliseconds contained by this `Duration`.
268 /// # #![feature(duration_as_u128)]
269 /// use std::time::Duration;
271 /// let duration = Duration::new(5, 730023852);
272 /// assert_eq!(duration.as_millis(), 5730);
274 #[unstable(feature = "duration_as_u128", issue = "50202")]
276 pub const fn as_millis(&self) -> u128 {
277 self.secs as u128 * MILLIS_PER_SEC as u128 + (self.nanos / NANOS_PER_MILLI) as u128
280 /// Returns the total number of whole microseconds contained by this `Duration`.
285 /// # #![feature(duration_as_u128)]
286 /// use std::time::Duration;
288 /// let duration = Duration::new(5, 730023852);
289 /// assert_eq!(duration.as_micros(), 5730023);
291 #[unstable(feature = "duration_as_u128", issue = "50202")]
293 pub const fn as_micros(&self) -> u128 {
294 self.secs as u128 * MICROS_PER_SEC as u128 + (self.nanos / NANOS_PER_MICRO) as u128
297 /// Returns the total number of nanoseconds contained by this `Duration`.
302 /// # #![feature(duration_as_u128)]
303 /// use std::time::Duration;
305 /// let duration = Duration::new(5, 730023852);
306 /// assert_eq!(duration.as_nanos(), 5730023852);
308 #[unstable(feature = "duration_as_u128", issue = "50202")]
310 pub const fn as_nanos(&self) -> u128 {
311 self.secs as u128 * NANOS_PER_SEC as u128 + self.nanos as u128
314 /// Checked `Duration` addition. Computes `self + other`, returning [`None`]
315 /// if overflow occurred.
317 /// [`None`]: ../../std/option/enum.Option.html#variant.None
324 /// use std::time::Duration;
326 /// assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1)));
327 /// assert_eq!(Duration::new(1, 0).checked_add(Duration::new(std::u64::MAX, 0)), None);
329 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
331 pub fn checked_add(self, rhs: Duration) -> Option<Duration> {
332 if let Some(mut secs) = self.secs.checked_add(rhs.secs) {
333 let mut nanos = self.nanos + rhs.nanos;
334 if nanos >= NANOS_PER_SEC {
335 nanos -= NANOS_PER_SEC;
336 if let Some(new_secs) = secs.checked_add(1) {
342 debug_assert!(nanos < NANOS_PER_SEC);
352 /// Checked `Duration` subtraction. Computes `self - other`, returning [`None`]
353 /// if the result would be negative or if overflow occurred.
355 /// [`None`]: ../../std/option/enum.Option.html#variant.None
362 /// use std::time::Duration;
364 /// assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1)));
365 /// assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None);
367 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
369 pub fn checked_sub(self, rhs: Duration) -> Option<Duration> {
370 if let Some(mut secs) = self.secs.checked_sub(rhs.secs) {
371 let nanos = if self.nanos >= rhs.nanos {
372 self.nanos - rhs.nanos
374 if let Some(sub_secs) = secs.checked_sub(1) {
376 self.nanos + NANOS_PER_SEC - rhs.nanos
381 debug_assert!(nanos < NANOS_PER_SEC);
382 Some(Duration { secs, nanos })
388 /// Checked `Duration` multiplication. Computes `self * other`, returning
389 /// [`None`] if overflow occurred.
391 /// [`None`]: ../../std/option/enum.Option.html#variant.None
398 /// use std::time::Duration;
400 /// assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2)));
401 /// assert_eq!(Duration::new(std::u64::MAX - 1, 0).checked_mul(2), None);
403 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
405 pub fn checked_mul(self, rhs: u32) -> Option<Duration> {
406 // Multiply nanoseconds as u64, because it cannot overflow that way.
407 let total_nanos = self.nanos as u64 * rhs as u64;
408 let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
409 let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
410 if let Some(secs) = self.secs
411 .checked_mul(rhs as u64)
412 .and_then(|s| s.checked_add(extra_secs)) {
413 debug_assert!(nanos < NANOS_PER_SEC);
423 /// Checked `Duration` division. Computes `self / other`, returning [`None`]
426 /// [`None`]: ../../std/option/enum.Option.html#variant.None
433 /// use std::time::Duration;
435 /// assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
436 /// assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
437 /// assert_eq!(Duration::new(2, 0).checked_div(0), None);
439 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
441 pub fn checked_div(self, rhs: u32) -> Option<Duration> {
443 let secs = self.secs / (rhs as u64);
444 let carry = self.secs - secs * (rhs as u64);
445 let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64);
446 let nanos = self.nanos / rhs + (extra_nanos as u32);
447 debug_assert!(nanos < NANOS_PER_SEC);
448 Some(Duration { secs, nanos })
454 /// Returns the number of seconds contained by this `Duration` as `f64`.
456 /// The returned value does include the fractional (nanosecond) part of the duration.
460 /// #![feature(duration_float)]
461 /// use std::time::Duration;
463 /// let dur = Duration::new(2, 700_000_000);
464 /// assert_eq!(dur.as_float_secs(), 2.7);
466 #[unstable(feature = "duration_float", issue = "54361")]
468 pub const fn as_float_secs(&self) -> f64 {
469 (self.secs as f64) + (self.nanos as f64) / (NANOS_PER_SEC as f64)
472 /// Creates a new `Duration` from the specified number of seconds.
475 /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
479 /// #![feature(duration_float)]
480 /// use std::time::Duration;
482 /// let dur = Duration::from_float_secs(2.7);
483 /// assert_eq!(dur, Duration::new(2, 700_000_000));
485 #[unstable(feature = "duration_float", issue = "54361")]
487 pub fn from_float_secs(secs: f64) -> Duration {
488 let nanos = secs * (NANOS_PER_SEC as f64);
489 if !nanos.is_finite() {
490 panic!("got non-finite value when converting float to duration");
492 if nanos >= MAX_NANOS_F64 {
493 panic!("overflow when converting float to duration");
496 panic!("underflow when converting float to duration");
498 let nanos = nanos as u128;
500 secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
501 nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
505 /// Multiply `Duration` by `f64`.
508 /// This method will panic if result is not finite, negative or overflows `Duration`.
512 /// #![feature(duration_float)]
513 /// use std::time::Duration;
515 /// let dur = Duration::new(2, 700_000_000);
516 /// assert_eq!(dur.mul_f64(3.14), Duration::new(8, 478_000_000));
517 /// assert_eq!(dur.mul_f64(3.14e5), Duration::new(847_800, 0));
519 #[unstable(feature = "duration_float", issue = "54361")]
521 pub fn mul_f64(self, rhs: f64) -> Duration {
522 Duration::from_float_secs(rhs * self.as_float_secs())
525 /// Divide `Duration` by `f64`.
528 /// This method will panic if result is not finite, negative or overflows `Duration`.
532 /// #![feature(duration_float)]
533 /// use std::time::Duration;
535 /// let dur = Duration::new(2, 700_000_000);
536 /// assert_eq!(dur.div_f64(3.14), Duration::new(0, 859_872_611));
537 /// // note that truncation is used, not rounding
538 /// assert_eq!(dur.div_f64(3.14e5), Duration::new(0, 8_598));
540 #[unstable(feature = "duration_float", issue = "54361")]
542 pub fn div_f64(self, rhs: f64) -> Duration {
543 Duration::from_float_secs(self.as_float_secs() / rhs)
546 /// Divide `Duration` by `Duration` and return `f64`.
550 /// #![feature(duration_float)]
551 /// use std::time::Duration;
553 /// let dur1 = Duration::new(2, 700_000_000);
554 /// let dur2 = Duration::new(5, 400_000_000);
555 /// assert_eq!(dur1.div_duration(dur2), 0.5);
557 #[unstable(feature = "duration_float", issue = "54361")]
559 pub fn div_duration(self, rhs: Duration) -> f64 {
560 self.as_float_secs() / rhs.as_float_secs()
564 #[stable(feature = "duration", since = "1.3.0")]
565 impl Add for Duration {
566 type Output = Duration;
568 fn add(self, rhs: Duration) -> Duration {
569 self.checked_add(rhs).expect("overflow when adding durations")
573 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
574 impl AddAssign for Duration {
575 fn add_assign(&mut self, rhs: Duration) {
580 #[stable(feature = "duration", since = "1.3.0")]
581 impl Sub for Duration {
582 type Output = Duration;
584 fn sub(self, rhs: Duration) -> Duration {
585 self.checked_sub(rhs).expect("overflow when subtracting durations")
589 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
590 impl SubAssign for Duration {
591 fn sub_assign(&mut self, rhs: Duration) {
596 #[stable(feature = "duration", since = "1.3.0")]
597 impl Mul<u32> for Duration {
598 type Output = Duration;
600 fn mul(self, rhs: u32) -> Duration {
601 self.checked_mul(rhs).expect("overflow when multiplying duration by scalar")
605 #[stable(feature = "symmetric_u32_duration_mul", since = "1.31.0")]
606 impl Mul<Duration> for u32 {
607 type Output = Duration;
609 fn mul(self, rhs: Duration) -> Duration {
614 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
615 impl MulAssign<u32> for Duration {
616 fn mul_assign(&mut self, rhs: u32) {
621 #[stable(feature = "duration", since = "1.3.0")]
622 impl Div<u32> for Duration {
623 type Output = Duration;
625 fn div(self, rhs: u32) -> Duration {
626 self.checked_div(rhs).expect("divide by zero error when dividing duration by scalar")
630 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
631 impl DivAssign<u32> for Duration {
632 fn div_assign(&mut self, rhs: u32) {
637 macro_rules! sum_durations {
639 let mut total_secs: u64 = 0;
640 let mut total_nanos: u64 = 0;
643 total_secs = total_secs
644 .checked_add(entry.secs)
645 .expect("overflow in iter::sum over durations");
646 total_nanos = match total_nanos.checked_add(entry.nanos as u64) {
649 total_secs = total_secs
650 .checked_add(total_nanos / NANOS_PER_SEC as u64)
651 .expect("overflow in iter::sum over durations");
652 (total_nanos % NANOS_PER_SEC as u64) + entry.nanos as u64
656 total_secs = total_secs
657 .checked_add(total_nanos / NANOS_PER_SEC as u64)
658 .expect("overflow in iter::sum over durations");
659 total_nanos = total_nanos % NANOS_PER_SEC as u64;
662 nanos: total_nanos as u32,
667 #[stable(feature = "duration_sum", since = "1.16.0")]
668 impl Sum for Duration {
669 fn sum<I: Iterator<Item=Duration>>(iter: I) -> Duration {
674 #[stable(feature = "duration_sum", since = "1.16.0")]
675 impl<'a> Sum<&'a Duration> for Duration {
676 fn sum<I: Iterator<Item=&'a Duration>>(iter: I) -> Duration {
681 #[stable(feature = "duration_debug_impl", since = "1.27.0")]
682 impl fmt::Debug for Duration {
683 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
684 /// Formats a floating point number in decimal notation.
686 /// The number is given as the `integer_part` and a fractional part.
687 /// The value of the fractional part is `fractional_part / divisor`. So
688 /// `integer_part` = 3, `fractional_part` = 12 and `divisor` = 100
689 /// represents the number `3.012`. Trailing zeros are omitted.
691 /// `divisor` must not be above 100_000_000. It also should be a power
692 /// of 10, everything else doesn't make sense. `fractional_part` has
693 /// to be less than `10 * divisor`!
695 f: &mut fmt::Formatter,
696 mut integer_part: u64,
697 mut fractional_part: u32,
700 // Encode the fractional part into a temporary buffer. The buffer
701 // only need to hold 9 elements, because `fractional_part` has to
702 // be smaller than 10^9. The buffer is prefilled with '0' digits
703 // to simplify the code below.
704 let mut buf = [b'0'; 9];
706 // The next digit is written at this position
709 // We keep writing digits into the buffer while there are non-zero
710 // digits left and we haven't written enough digits yet.
711 while fractional_part > 0 && pos < f.precision().unwrap_or(9) {
712 // Write new digit into the buffer
713 buf[pos] = b'0' + (fractional_part / divisor) as u8;
715 fractional_part %= divisor;
720 // If a precision < 9 was specified, there may be some non-zero
721 // digits left that weren't written into the buffer. In that case we
722 // need to perform rounding to match the semantics of printing
723 // normal floating point numbers. However, we only need to do work
724 // when rounding up. This happens if the first digit of the
725 // remaining ones is >= 5.
726 if fractional_part > 0 && fractional_part >= divisor * 5 {
727 // Round up the number contained in the buffer. We go through
728 // the buffer backwards and keep track of the carry.
729 let mut rev_pos = pos;
730 let mut carry = true;
731 while carry && rev_pos > 0 {
734 // If the digit in the buffer is not '9', we just need to
735 // increment it and can stop then (since we don't have a
736 // carry anymore). Otherwise, we set it to '0' (overflow)
738 if buf[rev_pos] < b'9' {
746 // If we still have the carry bit set, that means that we set
747 // the whole buffer to '0's and need to increment the integer
754 // Determine the end of the buffer: if precision is set, we just
755 // use as many digits from the buffer (capped to 9). If it isn't
756 // set, we only use all digits up to the last non-zero one.
757 let end = f.precision().map(|p| ::cmp::min(p, 9)).unwrap_or(pos);
759 // If we haven't emitted a single fractional digit and the precision
760 // wasn't set to a non-zero value, we don't print the decimal point.
762 write!(f, "{}", integer_part)
764 // We are only writing ASCII digits into the buffer and it was
765 // initialized with '0's, so it contains valid UTF8.
767 ::str::from_utf8_unchecked(&buf[..end])
770 // If the user request a precision > 9, we pad '0's at the end.
771 let w = f.precision().unwrap_or(pos);
772 write!(f, "{}.{:0<width$}", integer_part, s, width = w)
776 // Print leading '+' sign if requested
782 fmt_decimal(f, self.secs, self.nanos, 100_000_000)?;
784 } else if self.nanos >= 1_000_000 {
785 fmt_decimal(f, self.nanos as u64 / 1_000_000, self.nanos % 1_000_000, 100_000)?;
787 } else if self.nanos >= 1_000 {
788 fmt_decimal(f, self.nanos as u64 / 1_000, self.nanos % 1_000, 100)?;
791 fmt_decimal(f, self.nanos as u64, 0, 1)?;