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 /// The duration of one second.
27 #[unstable(feature = "duration_constants", issue = "57391")]
28 pub const SECOND: Duration = Duration::from_secs(1);
30 /// The duration of one millisecond.
31 #[unstable(feature = "duration_constants", issue = "57391")]
32 pub const MILLISECOND: Duration = Duration::from_millis(1);
34 /// The duration of one microsecond.
35 #[unstable(feature = "duration_constants", issue = "57391")]
36 pub const MICROSECOND: Duration = Duration::from_micros(1);
38 /// The duration of one nanosecond.
39 #[unstable(feature = "duration_constants", issue = "57391")]
40 pub const NANOSECOND: Duration = Duration::from_nanos(1);
42 /// A `Duration` type to represent a span of time, typically used for system
45 /// Each `Duration` is composed of a whole number of seconds and a fractional part
46 /// represented in nanoseconds. If the underlying system does not support
47 /// nanosecond-level precision, APIs binding a system timeout will typically round up
48 /// the number of nanoseconds.
50 /// `Duration`s implement many common traits, including [`Add`], [`Sub`], and other
53 /// [`Add`]: ../../std/ops/trait.Add.html
54 /// [`Sub`]: ../../std/ops/trait.Sub.html
55 /// [`ops`]: ../../std/ops/index.html
60 /// use std::time::Duration;
62 /// let five_seconds = Duration::new(5, 0);
63 /// let five_seconds_and_five_nanos = five_seconds + Duration::new(0, 5);
65 /// assert_eq!(five_seconds_and_five_nanos.as_secs(), 5);
66 /// assert_eq!(five_seconds_and_five_nanos.subsec_nanos(), 5);
68 /// let ten_millis = Duration::from_millis(10);
70 #[stable(feature = "duration", since = "1.3.0")]
71 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
74 nanos: u32, // Always 0 <= nanos < NANOS_PER_SEC
78 /// Creates a new `Duration` from the specified number of whole seconds and
79 /// additional nanoseconds.
81 /// If the number of nanoseconds is greater than 1 billion (the number of
82 /// nanoseconds in a second), then it will carry over into the seconds provided.
86 /// This constructor will panic if the carry from the nanoseconds overflows
87 /// the seconds counter.
92 /// use std::time::Duration;
94 /// let five_seconds = Duration::new(5, 0);
96 #[stable(feature = "duration", since = "1.3.0")]
98 pub fn new(secs: u64, nanos: u32) -> Duration {
99 let secs = secs.checked_add((nanos / NANOS_PER_SEC) as u64)
100 .expect("overflow in Duration::new");
101 let nanos = nanos % NANOS_PER_SEC;
102 Duration { secs, nanos }
105 /// Creates a new `Duration` from the specified number of whole seconds.
110 /// use std::time::Duration;
112 /// let duration = Duration::from_secs(5);
114 /// assert_eq!(5, duration.as_secs());
115 /// assert_eq!(0, duration.subsec_nanos());
117 #[stable(feature = "duration", since = "1.3.0")]
120 pub const fn from_secs(secs: u64) -> Duration {
121 Duration { secs, nanos: 0 }
124 /// Creates a new `Duration` from the specified number of milliseconds.
129 /// use std::time::Duration;
131 /// let duration = Duration::from_millis(2569);
133 /// assert_eq!(2, duration.as_secs());
134 /// assert_eq!(569_000_000, duration.subsec_nanos());
136 #[stable(feature = "duration", since = "1.3.0")]
139 pub const fn from_millis(millis: u64) -> Duration {
141 secs: millis / MILLIS_PER_SEC,
142 nanos: ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI,
146 /// Creates a new `Duration` from the specified number of microseconds.
151 /// use std::time::Duration;
153 /// let duration = Duration::from_micros(1_000_002);
155 /// assert_eq!(1, duration.as_secs());
156 /// assert_eq!(2000, duration.subsec_nanos());
158 #[stable(feature = "duration_from_micros", since = "1.27.0")]
161 pub const fn from_micros(micros: u64) -> Duration {
163 secs: micros / MICROS_PER_SEC,
164 nanos: ((micros % MICROS_PER_SEC) as u32) * NANOS_PER_MICRO,
168 /// Creates a new `Duration` from the specified number of nanoseconds.
173 /// use std::time::Duration;
175 /// let duration = Duration::from_nanos(1_000_000_123);
177 /// assert_eq!(1, duration.as_secs());
178 /// assert_eq!(123, duration.subsec_nanos());
180 #[stable(feature = "duration_extras", since = "1.27.0")]
183 pub const fn from_nanos(nanos: u64) -> Duration {
185 secs: nanos / (NANOS_PER_SEC as u64),
186 nanos: (nanos % (NANOS_PER_SEC as u64)) as u32,
190 /// Returns the number of _whole_ seconds contained by this `Duration`.
192 /// The returned value does not include the fractional (nanosecond) part of the
193 /// duration, which can be obtained using [`subsec_nanos`].
198 /// use std::time::Duration;
200 /// let duration = Duration::new(5, 730023852);
201 /// assert_eq!(duration.as_secs(), 5);
204 /// To determine the total number of seconds represented by the `Duration`,
205 /// use `as_secs` in combination with [`subsec_nanos`]:
208 /// use std::time::Duration;
210 /// let duration = Duration::new(5, 730023852);
212 /// assert_eq!(5.730023852,
213 /// duration.as_secs() as f64
214 /// + duration.subsec_nanos() as f64 * 1e-9);
217 /// [`subsec_nanos`]: #method.subsec_nanos
218 #[stable(feature = "duration", since = "1.3.0")]
220 pub const fn as_secs(&self) -> u64 { self.secs }
222 /// Returns the fractional part of this `Duration`, in whole milliseconds.
224 /// This method does **not** return the length of the duration when
225 /// represented by milliseconds. The returned number always represents a
226 /// fractional portion of a second (i.e., it is less than one thousand).
231 /// use std::time::Duration;
233 /// let duration = Duration::from_millis(5432);
234 /// assert_eq!(duration.as_secs(), 5);
235 /// assert_eq!(duration.subsec_millis(), 432);
237 #[stable(feature = "duration_extras", since = "1.27.0")]
239 pub const fn subsec_millis(&self) -> u32 { self.nanos / NANOS_PER_MILLI }
241 /// Returns the fractional part of this `Duration`, in whole microseconds.
243 /// This method does **not** return the length of the duration when
244 /// represented by microseconds. The returned number always represents a
245 /// fractional portion of a second (i.e., it is less than one million).
250 /// use std::time::Duration;
252 /// let duration = Duration::from_micros(1_234_567);
253 /// assert_eq!(duration.as_secs(), 1);
254 /// assert_eq!(duration.subsec_micros(), 234_567);
256 #[stable(feature = "duration_extras", since = "1.27.0")]
258 pub const fn subsec_micros(&self) -> u32 { self.nanos / NANOS_PER_MICRO }
260 /// Returns the fractional part of this `Duration`, in nanoseconds.
262 /// This method does **not** return the length of the duration when
263 /// represented by nanoseconds. The returned number always represents a
264 /// fractional portion of a second (i.e., it is less than one billion).
269 /// use std::time::Duration;
271 /// let duration = Duration::from_millis(5010);
272 /// assert_eq!(duration.as_secs(), 5);
273 /// assert_eq!(duration.subsec_nanos(), 10_000_000);
275 #[stable(feature = "duration", since = "1.3.0")]
277 pub const fn subsec_nanos(&self) -> u32 { self.nanos }
279 /// Returns the total number of whole milliseconds contained by this `Duration`.
284 /// use std::time::Duration;
286 /// let duration = Duration::new(5, 730023852);
287 /// assert_eq!(duration.as_millis(), 5730);
289 #[stable(feature = "duration_as_u128", since = "1.33.0")]
291 pub const fn as_millis(&self) -> u128 {
292 self.secs as u128 * MILLIS_PER_SEC as u128 + (self.nanos / NANOS_PER_MILLI) as u128
295 /// Returns the total number of whole microseconds contained by this `Duration`.
300 /// use std::time::Duration;
302 /// let duration = Duration::new(5, 730023852);
303 /// assert_eq!(duration.as_micros(), 5730023);
305 #[stable(feature = "duration_as_u128", since = "1.33.0")]
307 pub const fn as_micros(&self) -> u128 {
308 self.secs as u128 * MICROS_PER_SEC as u128 + (self.nanos / NANOS_PER_MICRO) as u128
311 /// Returns the total number of nanoseconds contained by this `Duration`.
316 /// use std::time::Duration;
318 /// let duration = Duration::new(5, 730023852);
319 /// assert_eq!(duration.as_nanos(), 5730023852);
321 #[stable(feature = "duration_as_u128", since = "1.33.0")]
323 pub const fn as_nanos(&self) -> u128 {
324 self.secs as u128 * NANOS_PER_SEC as u128 + self.nanos as u128
327 /// Checked `Duration` addition. Computes `self + other`, returning [`None`]
328 /// if overflow occurred.
330 /// [`None`]: ../../std/option/enum.Option.html#variant.None
337 /// use std::time::Duration;
339 /// assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1)));
340 /// assert_eq!(Duration::new(1, 0).checked_add(Duration::new(std::u64::MAX, 0)), None);
342 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
344 pub fn checked_add(self, rhs: Duration) -> Option<Duration> {
345 if let Some(mut secs) = self.secs.checked_add(rhs.secs) {
346 let mut nanos = self.nanos + rhs.nanos;
347 if nanos >= NANOS_PER_SEC {
348 nanos -= NANOS_PER_SEC;
349 if let Some(new_secs) = secs.checked_add(1) {
355 debug_assert!(nanos < NANOS_PER_SEC);
365 /// Checked `Duration` subtraction. Computes `self - other`, returning [`None`]
366 /// if the result would be negative or if overflow occurred.
368 /// [`None`]: ../../std/option/enum.Option.html#variant.None
375 /// use std::time::Duration;
377 /// assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1)));
378 /// assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None);
380 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
382 pub fn checked_sub(self, rhs: Duration) -> Option<Duration> {
383 if let Some(mut secs) = self.secs.checked_sub(rhs.secs) {
384 let nanos = if self.nanos >= rhs.nanos {
385 self.nanos - rhs.nanos
387 if let Some(sub_secs) = secs.checked_sub(1) {
389 self.nanos + NANOS_PER_SEC - rhs.nanos
394 debug_assert!(nanos < NANOS_PER_SEC);
395 Some(Duration { secs, nanos })
401 /// Checked `Duration` multiplication. Computes `self * other`, returning
402 /// [`None`] if overflow occurred.
404 /// [`None`]: ../../std/option/enum.Option.html#variant.None
411 /// use std::time::Duration;
413 /// assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2)));
414 /// assert_eq!(Duration::new(std::u64::MAX - 1, 0).checked_mul(2), None);
416 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
418 pub fn checked_mul(self, rhs: u32) -> Option<Duration> {
419 // Multiply nanoseconds as u64, because it cannot overflow that way.
420 let total_nanos = self.nanos as u64 * rhs as u64;
421 let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
422 let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
423 if let Some(secs) = self.secs
424 .checked_mul(rhs as u64)
425 .and_then(|s| s.checked_add(extra_secs)) {
426 debug_assert!(nanos < NANOS_PER_SEC);
436 /// Checked `Duration` division. Computes `self / other`, returning [`None`]
439 /// [`None`]: ../../std/option/enum.Option.html#variant.None
446 /// use std::time::Duration;
448 /// assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
449 /// assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
450 /// assert_eq!(Duration::new(2, 0).checked_div(0), None);
452 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
454 pub fn checked_div(self, rhs: u32) -> Option<Duration> {
456 let secs = self.secs / (rhs as u64);
457 let carry = self.secs - secs * (rhs as u64);
458 let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64);
459 let nanos = self.nanos / rhs + (extra_nanos as u32);
460 debug_assert!(nanos < NANOS_PER_SEC);
461 Some(Duration { secs, nanos })
467 /// Returns the number of seconds contained by this `Duration` as `f64`.
469 /// The returned value does include the fractional (nanosecond) part of the duration.
473 /// #![feature(duration_float)]
474 /// use std::time::Duration;
476 /// let dur = Duration::new(2, 700_000_000);
477 /// assert_eq!(dur.as_float_secs(), 2.7);
479 #[unstable(feature = "duration_float", issue = "54361")]
481 pub const fn as_float_secs(&self) -> f64 {
482 (self.secs as f64) + (self.nanos as f64) / (NANOS_PER_SEC as f64)
485 /// Creates a new `Duration` from the specified number of seconds.
488 /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
492 /// #![feature(duration_float)]
493 /// use std::time::Duration;
495 /// let dur = Duration::from_float_secs(2.7);
496 /// assert_eq!(dur, Duration::new(2, 700_000_000));
498 #[unstable(feature = "duration_float", issue = "54361")]
500 pub fn from_float_secs(secs: f64) -> Duration {
501 let nanos = secs * (NANOS_PER_SEC as f64);
502 if !nanos.is_finite() {
503 panic!("got non-finite value when converting float to duration");
505 if nanos >= MAX_NANOS_F64 {
506 panic!("overflow when converting float to duration");
509 panic!("underflow when converting float to duration");
511 let nanos = nanos as u128;
513 secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
514 nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
518 /// Multiply `Duration` by `f64`.
521 /// This method will panic if result is not finite, negative or overflows `Duration`.
525 /// #![feature(duration_float)]
526 /// use std::time::Duration;
528 /// let dur = Duration::new(2, 700_000_000);
529 /// assert_eq!(dur.mul_f64(3.14), Duration::new(8, 478_000_000));
530 /// assert_eq!(dur.mul_f64(3.14e5), Duration::new(847_800, 0));
532 #[unstable(feature = "duration_float", issue = "54361")]
534 pub fn mul_f64(self, rhs: f64) -> Duration {
535 Duration::from_float_secs(rhs * self.as_float_secs())
538 /// Divide `Duration` by `f64`.
541 /// This method will panic if result is not finite, negative or overflows `Duration`.
545 /// #![feature(duration_float)]
546 /// use std::time::Duration;
548 /// let dur = Duration::new(2, 700_000_000);
549 /// assert_eq!(dur.div_f64(3.14), Duration::new(0, 859_872_611));
550 /// // note that truncation is used, not rounding
551 /// assert_eq!(dur.div_f64(3.14e5), Duration::new(0, 8_598));
553 #[unstable(feature = "duration_float", issue = "54361")]
555 pub fn div_f64(self, rhs: f64) -> Duration {
556 Duration::from_float_secs(self.as_float_secs() / rhs)
559 /// Divide `Duration` by `Duration` and return `f64`.
563 /// #![feature(duration_float)]
564 /// use std::time::Duration;
566 /// let dur1 = Duration::new(2, 700_000_000);
567 /// let dur2 = Duration::new(5, 400_000_000);
568 /// assert_eq!(dur1.div_duration(dur2), 0.5);
570 #[unstable(feature = "duration_float", issue = "54361")]
572 pub fn div_duration(self, rhs: Duration) -> f64 {
573 self.as_float_secs() / rhs.as_float_secs()
577 #[stable(feature = "duration", since = "1.3.0")]
578 impl Add for Duration {
579 type Output = Duration;
581 fn add(self, rhs: Duration) -> Duration {
582 self.checked_add(rhs).expect("overflow when adding durations")
586 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
587 impl AddAssign for Duration {
588 fn add_assign(&mut self, rhs: Duration) {
593 #[stable(feature = "duration", since = "1.3.0")]
594 impl Sub for Duration {
595 type Output = Duration;
597 fn sub(self, rhs: Duration) -> Duration {
598 self.checked_sub(rhs).expect("overflow when subtracting durations")
602 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
603 impl SubAssign for Duration {
604 fn sub_assign(&mut self, rhs: Duration) {
609 #[stable(feature = "duration", since = "1.3.0")]
610 impl Mul<u32> for Duration {
611 type Output = Duration;
613 fn mul(self, rhs: u32) -> Duration {
614 self.checked_mul(rhs).expect("overflow when multiplying duration by scalar")
618 #[stable(feature = "symmetric_u32_duration_mul", since = "1.31.0")]
619 impl Mul<Duration> for u32 {
620 type Output = Duration;
622 fn mul(self, rhs: Duration) -> Duration {
627 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
628 impl MulAssign<u32> for Duration {
629 fn mul_assign(&mut self, rhs: u32) {
634 #[stable(feature = "duration", since = "1.3.0")]
635 impl Div<u32> for Duration {
636 type Output = Duration;
638 fn div(self, rhs: u32) -> Duration {
639 self.checked_div(rhs).expect("divide by zero error when dividing duration by scalar")
643 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
644 impl DivAssign<u32> for Duration {
645 fn div_assign(&mut self, rhs: u32) {
650 macro_rules! sum_durations {
652 let mut total_secs: u64 = 0;
653 let mut total_nanos: u64 = 0;
656 total_secs = total_secs
657 .checked_add(entry.secs)
658 .expect("overflow in iter::sum over durations");
659 total_nanos = match total_nanos.checked_add(entry.nanos as u64) {
662 total_secs = total_secs
663 .checked_add(total_nanos / NANOS_PER_SEC as u64)
664 .expect("overflow in iter::sum over durations");
665 (total_nanos % NANOS_PER_SEC as u64) + entry.nanos as u64
669 total_secs = total_secs
670 .checked_add(total_nanos / NANOS_PER_SEC as u64)
671 .expect("overflow in iter::sum over durations");
672 total_nanos = total_nanos % NANOS_PER_SEC as u64;
675 nanos: total_nanos as u32,
680 #[stable(feature = "duration_sum", since = "1.16.0")]
681 impl Sum for Duration {
682 fn sum<I: Iterator<Item=Duration>>(iter: I) -> Duration {
687 #[stable(feature = "duration_sum", since = "1.16.0")]
688 impl<'a> Sum<&'a Duration> for Duration {
689 fn sum<I: Iterator<Item=&'a Duration>>(iter: I) -> Duration {
694 #[stable(feature = "duration_debug_impl", since = "1.27.0")]
695 impl fmt::Debug for Duration {
696 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
697 /// Formats a floating point number in decimal notation.
699 /// The number is given as the `integer_part` and a fractional part.
700 /// The value of the fractional part is `fractional_part / divisor`. So
701 /// `integer_part` = 3, `fractional_part` = 12 and `divisor` = 100
702 /// represents the number `3.012`. Trailing zeros are omitted.
704 /// `divisor` must not be above 100_000_000. It also should be a power
705 /// of 10, everything else doesn't make sense. `fractional_part` has
706 /// to be less than `10 * divisor`!
708 f: &mut fmt::Formatter,
709 mut integer_part: u64,
710 mut fractional_part: u32,
713 // Encode the fractional part into a temporary buffer. The buffer
714 // only need to hold 9 elements, because `fractional_part` has to
715 // be smaller than 10^9. The buffer is prefilled with '0' digits
716 // to simplify the code below.
717 let mut buf = [b'0'; 9];
719 // The next digit is written at this position
722 // We keep writing digits into the buffer while there are non-zero
723 // digits left and we haven't written enough digits yet.
724 while fractional_part > 0 && pos < f.precision().unwrap_or(9) {
725 // Write new digit into the buffer
726 buf[pos] = b'0' + (fractional_part / divisor) as u8;
728 fractional_part %= divisor;
733 // If a precision < 9 was specified, there may be some non-zero
734 // digits left that weren't written into the buffer. In that case we
735 // need to perform rounding to match the semantics of printing
736 // normal floating point numbers. However, we only need to do work
737 // when rounding up. This happens if the first digit of the
738 // remaining ones is >= 5.
739 if fractional_part > 0 && fractional_part >= divisor * 5 {
740 // Round up the number contained in the buffer. We go through
741 // the buffer backwards and keep track of the carry.
742 let mut rev_pos = pos;
743 let mut carry = true;
744 while carry && rev_pos > 0 {
747 // If the digit in the buffer is not '9', we just need to
748 // increment it and can stop then (since we don't have a
749 // carry anymore). Otherwise, we set it to '0' (overflow)
751 if buf[rev_pos] < b'9' {
759 // If we still have the carry bit set, that means that we set
760 // the whole buffer to '0's and need to increment the integer
767 // Determine the end of the buffer: if precision is set, we just
768 // use as many digits from the buffer (capped to 9). If it isn't
769 // set, we only use all digits up to the last non-zero one.
770 let end = f.precision().map(|p| ::cmp::min(p, 9)).unwrap_or(pos);
772 // If we haven't emitted a single fractional digit and the precision
773 // wasn't set to a non-zero value, we don't print the decimal point.
775 write!(f, "{}", integer_part)
777 // We are only writing ASCII digits into the buffer and it was
778 // initialized with '0's, so it contains valid UTF8.
780 ::str::from_utf8_unchecked(&buf[..end])
783 // If the user request a precision > 9, we pad '0's at the end.
784 let w = f.precision().unwrap_or(pos);
785 write!(f, "{}.{:0<width$}", integer_part, s, width = w)
789 // Print leading '+' sign if requested
795 fmt_decimal(f, self.secs, self.nanos, 100_000_000)?;
797 } else if self.nanos >= 1_000_000 {
798 fmt_decimal(f, self.nanos as u64 / 1_000_000, self.nanos % 1_000_000, 100_000)?;
800 } else if self.nanos >= 1_000 {
801 fmt_decimal(f, self.nanos as u64 / 1_000, self.nanos % 1_000, 100)?;
804 fmt_decimal(f, self.nanos as u64, 0, 1)?;