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 /// use std::time::Duration;
270 /// let duration = Duration::new(5, 730023852);
271 /// assert_eq!(duration.as_millis(), 5730);
273 #[stable(feature = "duration_as_u128", since = "1.33.0")]
275 pub const fn as_millis(&self) -> u128 {
276 self.secs as u128 * MILLIS_PER_SEC as u128 + (self.nanos / NANOS_PER_MILLI) as u128
279 /// Returns the total number of whole microseconds contained by this `Duration`.
284 /// use std::time::Duration;
286 /// let duration = Duration::new(5, 730023852);
287 /// assert_eq!(duration.as_micros(), 5730023);
289 #[stable(feature = "duration_as_u128", since = "1.33.0")]
291 pub const fn as_micros(&self) -> u128 {
292 self.secs as u128 * MICROS_PER_SEC as u128 + (self.nanos / NANOS_PER_MICRO) as u128
295 /// Returns the total number of nanoseconds contained by this `Duration`.
300 /// use std::time::Duration;
302 /// let duration = Duration::new(5, 730023852);
303 /// assert_eq!(duration.as_nanos(), 5730023852);
305 #[stable(feature = "duration_as_u128", since = "1.33.0")]
307 pub const fn as_nanos(&self) -> u128 {
308 self.secs as u128 * NANOS_PER_SEC as u128 + self.nanos as u128
311 /// Checked `Duration` addition. Computes `self + other`, returning [`None`]
312 /// if overflow occurred.
314 /// [`None`]: ../../std/option/enum.Option.html#variant.None
321 /// use std::time::Duration;
323 /// assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1)));
324 /// assert_eq!(Duration::new(1, 0).checked_add(Duration::new(std::u64::MAX, 0)), None);
326 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
328 pub fn checked_add(self, rhs: Duration) -> Option<Duration> {
329 if let Some(mut secs) = self.secs.checked_add(rhs.secs) {
330 let mut nanos = self.nanos + rhs.nanos;
331 if nanos >= NANOS_PER_SEC {
332 nanos -= NANOS_PER_SEC;
333 if let Some(new_secs) = secs.checked_add(1) {
339 debug_assert!(nanos < NANOS_PER_SEC);
349 /// Checked `Duration` subtraction. Computes `self - other`, returning [`None`]
350 /// if the result would be negative or if overflow occurred.
352 /// [`None`]: ../../std/option/enum.Option.html#variant.None
359 /// use std::time::Duration;
361 /// assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1)));
362 /// assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None);
364 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
366 pub fn checked_sub(self, rhs: Duration) -> Option<Duration> {
367 if let Some(mut secs) = self.secs.checked_sub(rhs.secs) {
368 let nanos = if self.nanos >= rhs.nanos {
369 self.nanos - rhs.nanos
371 if let Some(sub_secs) = secs.checked_sub(1) {
373 self.nanos + NANOS_PER_SEC - rhs.nanos
378 debug_assert!(nanos < NANOS_PER_SEC);
379 Some(Duration { secs, nanos })
385 /// Checked `Duration` multiplication. Computes `self * other`, returning
386 /// [`None`] if overflow occurred.
388 /// [`None`]: ../../std/option/enum.Option.html#variant.None
395 /// use std::time::Duration;
397 /// assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2)));
398 /// assert_eq!(Duration::new(std::u64::MAX - 1, 0).checked_mul(2), None);
400 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
402 pub fn checked_mul(self, rhs: u32) -> Option<Duration> {
403 // Multiply nanoseconds as u64, because it cannot overflow that way.
404 let total_nanos = self.nanos as u64 * rhs as u64;
405 let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
406 let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
407 if let Some(secs) = self.secs
408 .checked_mul(rhs as u64)
409 .and_then(|s| s.checked_add(extra_secs)) {
410 debug_assert!(nanos < NANOS_PER_SEC);
420 /// Checked `Duration` division. Computes `self / other`, returning [`None`]
423 /// [`None`]: ../../std/option/enum.Option.html#variant.None
430 /// use std::time::Duration;
432 /// assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
433 /// assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
434 /// assert_eq!(Duration::new(2, 0).checked_div(0), None);
436 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
438 pub fn checked_div(self, rhs: u32) -> Option<Duration> {
440 let secs = self.secs / (rhs as u64);
441 let carry = self.secs - secs * (rhs as u64);
442 let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64);
443 let nanos = self.nanos / rhs + (extra_nanos as u32);
444 debug_assert!(nanos < NANOS_PER_SEC);
445 Some(Duration { secs, nanos })
451 /// Returns the number of seconds contained by this `Duration` as `f64`.
453 /// The returned value does include the fractional (nanosecond) part of the duration.
457 /// #![feature(duration_float)]
458 /// use std::time::Duration;
460 /// let dur = Duration::new(2, 700_000_000);
461 /// assert_eq!(dur.as_float_secs(), 2.7);
463 #[unstable(feature = "duration_float", issue = "54361")]
465 pub const fn as_float_secs(&self) -> f64 {
466 (self.secs as f64) + (self.nanos as f64) / (NANOS_PER_SEC as f64)
469 /// Creates a new `Duration` from the specified number of seconds.
472 /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
476 /// #![feature(duration_float)]
477 /// use std::time::Duration;
479 /// let dur = Duration::from_float_secs(2.7);
480 /// assert_eq!(dur, Duration::new(2, 700_000_000));
482 #[unstable(feature = "duration_float", issue = "54361")]
484 pub fn from_float_secs(secs: f64) -> Duration {
485 let nanos = secs * (NANOS_PER_SEC as f64);
486 if !nanos.is_finite() {
487 panic!("got non-finite value when converting float to duration");
489 if nanos >= MAX_NANOS_F64 {
490 panic!("overflow when converting float to duration");
493 panic!("underflow when converting float to duration");
495 let nanos = nanos as u128;
497 secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
498 nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
502 /// Multiply `Duration` by `f64`.
505 /// This method will panic if result is not finite, negative or overflows `Duration`.
509 /// #![feature(duration_float)]
510 /// use std::time::Duration;
512 /// let dur = Duration::new(2, 700_000_000);
513 /// assert_eq!(dur.mul_f64(3.14), Duration::new(8, 478_000_000));
514 /// assert_eq!(dur.mul_f64(3.14e5), Duration::new(847_800, 0));
516 #[unstable(feature = "duration_float", issue = "54361")]
518 pub fn mul_f64(self, rhs: f64) -> Duration {
519 Duration::from_float_secs(rhs * self.as_float_secs())
522 /// Divide `Duration` by `f64`.
525 /// This method will panic if result is not finite, negative or overflows `Duration`.
529 /// #![feature(duration_float)]
530 /// use std::time::Duration;
532 /// let dur = Duration::new(2, 700_000_000);
533 /// assert_eq!(dur.div_f64(3.14), Duration::new(0, 859_872_611));
534 /// // note that truncation is used, not rounding
535 /// assert_eq!(dur.div_f64(3.14e5), Duration::new(0, 8_598));
537 #[unstable(feature = "duration_float", issue = "54361")]
539 pub fn div_f64(self, rhs: f64) -> Duration {
540 Duration::from_float_secs(self.as_float_secs() / rhs)
543 /// Divide `Duration` by `Duration` and return `f64`.
547 /// #![feature(duration_float)]
548 /// use std::time::Duration;
550 /// let dur1 = Duration::new(2, 700_000_000);
551 /// let dur2 = Duration::new(5, 400_000_000);
552 /// assert_eq!(dur1.div_duration(dur2), 0.5);
554 #[unstable(feature = "duration_float", issue = "54361")]
556 pub fn div_duration(self, rhs: Duration) -> f64 {
557 self.as_float_secs() / rhs.as_float_secs()
561 #[stable(feature = "duration", since = "1.3.0")]
562 impl Add for Duration {
563 type Output = Duration;
565 fn add(self, rhs: Duration) -> Duration {
566 self.checked_add(rhs).expect("overflow when adding durations")
570 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
571 impl AddAssign for Duration {
572 fn add_assign(&mut self, rhs: Duration) {
577 #[stable(feature = "duration", since = "1.3.0")]
578 impl Sub for Duration {
579 type Output = Duration;
581 fn sub(self, rhs: Duration) -> Duration {
582 self.checked_sub(rhs).expect("overflow when subtracting durations")
586 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
587 impl SubAssign for Duration {
588 fn sub_assign(&mut self, rhs: Duration) {
593 #[stable(feature = "duration", since = "1.3.0")]
594 impl Mul<u32> for Duration {
595 type Output = Duration;
597 fn mul(self, rhs: u32) -> Duration {
598 self.checked_mul(rhs).expect("overflow when multiplying duration by scalar")
602 #[stable(feature = "symmetric_u32_duration_mul", since = "1.31.0")]
603 impl Mul<Duration> for u32 {
604 type Output = Duration;
606 fn mul(self, rhs: Duration) -> Duration {
611 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
612 impl MulAssign<u32> for Duration {
613 fn mul_assign(&mut self, rhs: u32) {
618 #[stable(feature = "duration", since = "1.3.0")]
619 impl Div<u32> for Duration {
620 type Output = Duration;
622 fn div(self, rhs: u32) -> Duration {
623 self.checked_div(rhs).expect("divide by zero error when dividing duration by scalar")
627 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
628 impl DivAssign<u32> for Duration {
629 fn div_assign(&mut self, rhs: u32) {
634 macro_rules! sum_durations {
636 let mut total_secs: u64 = 0;
637 let mut total_nanos: u64 = 0;
640 total_secs = total_secs
641 .checked_add(entry.secs)
642 .expect("overflow in iter::sum over durations");
643 total_nanos = match total_nanos.checked_add(entry.nanos as u64) {
646 total_secs = total_secs
647 .checked_add(total_nanos / NANOS_PER_SEC as u64)
648 .expect("overflow in iter::sum over durations");
649 (total_nanos % NANOS_PER_SEC as u64) + entry.nanos as u64
653 total_secs = total_secs
654 .checked_add(total_nanos / NANOS_PER_SEC as u64)
655 .expect("overflow in iter::sum over durations");
656 total_nanos = total_nanos % NANOS_PER_SEC as u64;
659 nanos: total_nanos as u32,
664 #[stable(feature = "duration_sum", since = "1.16.0")]
665 impl Sum for Duration {
666 fn sum<I: Iterator<Item=Duration>>(iter: I) -> Duration {
671 #[stable(feature = "duration_sum", since = "1.16.0")]
672 impl<'a> Sum<&'a Duration> for Duration {
673 fn sum<I: Iterator<Item=&'a Duration>>(iter: I) -> Duration {
678 #[stable(feature = "duration_debug_impl", since = "1.27.0")]
679 impl fmt::Debug for Duration {
680 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
681 /// Formats a floating point number in decimal notation.
683 /// The number is given as the `integer_part` and a fractional part.
684 /// The value of the fractional part is `fractional_part / divisor`. So
685 /// `integer_part` = 3, `fractional_part` = 12 and `divisor` = 100
686 /// represents the number `3.012`. Trailing zeros are omitted.
688 /// `divisor` must not be above 100_000_000. It also should be a power
689 /// of 10, everything else doesn't make sense. `fractional_part` has
690 /// to be less than `10 * divisor`!
692 f: &mut fmt::Formatter,
693 mut integer_part: u64,
694 mut fractional_part: u32,
697 // Encode the fractional part into a temporary buffer. The buffer
698 // only need to hold 9 elements, because `fractional_part` has to
699 // be smaller than 10^9. The buffer is prefilled with '0' digits
700 // to simplify the code below.
701 let mut buf = [b'0'; 9];
703 // The next digit is written at this position
706 // We keep writing digits into the buffer while there are non-zero
707 // digits left and we haven't written enough digits yet.
708 while fractional_part > 0 && pos < f.precision().unwrap_or(9) {
709 // Write new digit into the buffer
710 buf[pos] = b'0' + (fractional_part / divisor) as u8;
712 fractional_part %= divisor;
717 // If a precision < 9 was specified, there may be some non-zero
718 // digits left that weren't written into the buffer. In that case we
719 // need to perform rounding to match the semantics of printing
720 // normal floating point numbers. However, we only need to do work
721 // when rounding up. This happens if the first digit of the
722 // remaining ones is >= 5.
723 if fractional_part > 0 && fractional_part >= divisor * 5 {
724 // Round up the number contained in the buffer. We go through
725 // the buffer backwards and keep track of the carry.
726 let mut rev_pos = pos;
727 let mut carry = true;
728 while carry && rev_pos > 0 {
731 // If the digit in the buffer is not '9', we just need to
732 // increment it and can stop then (since we don't have a
733 // carry anymore). Otherwise, we set it to '0' (overflow)
735 if buf[rev_pos] < b'9' {
743 // If we still have the carry bit set, that means that we set
744 // the whole buffer to '0's and need to increment the integer
751 // Determine the end of the buffer: if precision is set, we just
752 // use as many digits from the buffer (capped to 9). If it isn't
753 // set, we only use all digits up to the last non-zero one.
754 let end = f.precision().map(|p| ::cmp::min(p, 9)).unwrap_or(pos);
756 // If we haven't emitted a single fractional digit and the precision
757 // wasn't set to a non-zero value, we don't print the decimal point.
759 write!(f, "{}", integer_part)
761 // We are only writing ASCII digits into the buffer and it was
762 // initialized with '0's, so it contains valid UTF8.
764 ::str::from_utf8_unchecked(&buf[..end])
767 // If the user request a precision > 9, we pad '0's at the end.
768 let w = f.precision().unwrap_or(pos);
769 write!(f, "{}.{:0<width$}", integer_part, s, width = w)
773 // Print leading '+' sign if requested
779 fmt_decimal(f, self.secs, self.nanos, 100_000_000)?;
781 } else if self.nanos >= 1_000_000 {
782 fmt_decimal(f, self.nanos as u64 / 1_000_000, self.nanos % 1_000_000, 100_000)?;
784 } else if self.nanos >= 1_000 {
785 fmt_decimal(f, self.nanos as u64 / 1_000, self.nanos % 1_000, 100)?;
788 fmt_decimal(f, self.nanos as u64, 0, 1)?;