1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Temporal quantification.
16 //! use std::time::Duration;
18 //! let five_seconds = Duration::new(5, 0);
19 //! // both declarations are equivalent
20 //! assert_eq!(Duration::new(5, 0), Duration::from_secs(5));
23 #![stable(feature = "time", since = "1.3.0")]
27 use ops::{Add, Sub, AddAssign, SubAssign};
29 use sys_common::FromInner;
31 #[stable(feature = "time", since = "1.3.0")]
32 pub use core::time::Duration;
34 /// A measurement of a monotonically nondecreasing clock.
35 /// Opaque and useful only with `Duration`.
37 /// Instants are always guaranteed to be no less than any previously measured
38 /// instant when created, and are often useful for tasks such as measuring
39 /// benchmarks or timing how long an operation takes.
41 /// Note, however, that instants are not guaranteed to be **steady**. In other
42 /// words, each tick of the underlying clock may not be the same length (e.g.
43 /// some seconds may be longer than others). An instant may jump forwards or
44 /// experience time dilation (slow down or speed up), but it will never go
47 /// Instants are opaque types that can only be compared to one another. There is
48 /// no method to get "the number of seconds" from an instant. Instead, it only
49 /// allows measuring the duration between two instants (or comparing two
52 /// The size of an `Instant` struct may vary depending on the target operating
58 /// use std::time::{Duration, Instant};
59 /// use std::thread::sleep;
62 /// let now = Instant::now();
64 /// // we sleep for 2 seconds
65 /// sleep(Duration::new(2, 0));
67 /// println!("{}", now.elapsed().as_secs());
70 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
71 #[stable(feature = "time2", since = "1.8.0")]
72 pub struct Instant(time::Instant);
74 /// A measurement of the system clock, useful for talking to
75 /// external entities like the file system or other processes.
77 /// Distinct from the [`Instant`] type, this time measurement **is not
78 /// monotonic**. This means that you can save a file to the file system, then
79 /// save another file to the file system, **and the second file has a
80 /// `SystemTime` measurement earlier than the first**. In other words, an
81 /// operation that happens after another operation in real time may have an
82 /// earlier `SystemTime`!
84 /// Consequently, comparing two `SystemTime` instances to learn about the
85 /// duration between them returns a [`Result`] instead of an infallible [`Duration`]
86 /// to indicate that this sort of time drift may happen and needs to be handled.
88 /// Although a `SystemTime` cannot be directly inspected, the [`UNIX_EPOCH`]
89 /// constant is provided in this module as an anchor in time to learn
90 /// information about a `SystemTime`. By calculating the duration from this
91 /// fixed point in time, a `SystemTime` can be converted to a human-readable time,
92 /// or perhaps some other string representation.
94 /// The size of a `SystemTime` struct may vary depending on the target operating
97 /// [`Instant`]: ../../std/time/struct.Instant.html
98 /// [`Result`]: ../../std/result/enum.Result.html
99 /// [`Duration`]: ../../std/time/struct.Duration.html
100 /// [`UNIX_EPOCH`]: ../../std/time/constant.UNIX_EPOCH.html
105 /// use std::time::{Duration, SystemTime};
106 /// use std::thread::sleep;
109 /// let now = SystemTime::now();
111 /// // we sleep for 2 seconds
112 /// sleep(Duration::new(2, 0));
113 /// match now.elapsed() {
116 /// println!("{}", elapsed.as_secs());
119 /// // an error occurred!
120 /// println!("Error: {:?}", e);
125 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
126 #[stable(feature = "time2", since = "1.8.0")]
127 pub struct SystemTime(time::SystemTime);
129 /// An error returned from the `duration_since` and `elapsed` methods on
130 /// `SystemTime`, used to learn how far in the opposite direction a system time
136 /// use std::thread::sleep;
137 /// use std::time::{Duration, SystemTime};
139 /// let sys_time = SystemTime::now();
140 /// sleep(Duration::from_secs(1));
141 /// let new_sys_time = SystemTime::now();
142 /// match sys_time.duration_since(new_sys_time) {
144 /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
147 #[derive(Clone, Debug)]
148 #[stable(feature = "time2", since = "1.8.0")]
149 pub struct SystemTimeError(Duration);
152 /// Returns an instant corresponding to "now".
157 /// use std::time::Instant;
159 /// let now = Instant::now();
161 #[stable(feature = "time2", since = "1.8.0")]
162 pub fn now() -> Instant {
163 Instant(time::Instant::now())
166 /// Returns the amount of time elapsed from another instant to this one.
170 /// This function will panic if `earlier` is later than `self`.
175 /// use std::time::{Duration, Instant};
176 /// use std::thread::sleep;
178 /// let now = Instant::now();
179 /// sleep(Duration::new(1, 0));
180 /// let new_now = Instant::now();
181 /// println!("{:?}", new_now.duration_since(now));
183 #[stable(feature = "time2", since = "1.8.0")]
184 pub fn duration_since(&self, earlier: Instant) -> Duration {
185 self.0.sub_instant(&earlier.0)
188 /// Returns the amount of time elapsed since this instant was created.
192 /// This function may panic if the current time is earlier than this
193 /// instant, which is something that can happen if an `Instant` is
194 /// produced synthetically.
199 /// use std::thread::sleep;
200 /// use std::time::{Duration, Instant};
202 /// let instant = Instant::now();
203 /// let three_secs = Duration::from_secs(3);
204 /// sleep(three_secs);
205 /// assert!(instant.elapsed() >= three_secs);
207 #[stable(feature = "time2", since = "1.8.0")]
208 pub fn elapsed(&self) -> Duration {
209 Instant::now() - *self
213 #[stable(feature = "time2", since = "1.8.0")]
214 impl Add<Duration> for Instant {
215 type Output = Instant;
217 fn add(self, other: Duration) -> Instant {
218 Instant(self.0.add_duration(&other))
222 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
223 impl AddAssign<Duration> for Instant {
224 fn add_assign(&mut self, other: Duration) {
225 *self = *self + other;
229 #[stable(feature = "time2", since = "1.8.0")]
230 impl Sub<Duration> for Instant {
231 type Output = Instant;
233 fn sub(self, other: Duration) -> Instant {
234 Instant(self.0.sub_duration(&other))
238 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
239 impl SubAssign<Duration> for Instant {
240 fn sub_assign(&mut self, other: Duration) {
241 *self = *self - other;
245 #[stable(feature = "time2", since = "1.8.0")]
246 impl Sub<Instant> for Instant {
247 type Output = Duration;
249 fn sub(self, other: Instant) -> Duration {
250 self.duration_since(other)
254 #[stable(feature = "time2", since = "1.8.0")]
255 impl fmt::Debug for Instant {
256 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
262 /// An anchor in time which can be used to create new `SystemTime` instances or
263 /// learn about where in time a `SystemTime` lies.
265 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
266 /// respect to the system clock. Using `duration_since` on an existing
267 /// `SystemTime` instance can tell how far away from this point in time a
268 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
269 /// `SystemTime` instance to represent another fixed point in time.
274 /// use std::time::SystemTime;
276 /// match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
277 /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
278 /// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
281 #[stable(feature = "assoc_unix_epoch", since = "1.28.0")]
282 pub const UNIX_EPOCH: SystemTime = UNIX_EPOCH;
284 /// Returns the system time corresponding to "now".
289 /// use std::time::SystemTime;
291 /// let sys_time = SystemTime::now();
293 #[stable(feature = "time2", since = "1.8.0")]
294 pub fn now() -> SystemTime {
295 SystemTime(time::SystemTime::now())
298 /// Returns the amount of time elapsed from an earlier point in time.
300 /// This function may fail because measurements taken earlier are not
301 /// guaranteed to always be before later measurements (due to anomalies such
302 /// as the system clock being adjusted either forwards or backwards).
304 /// If successful, [`Ok`]`(`[`Duration`]`)` is returned where the duration represents
305 /// the amount of time elapsed from the specified measurement to this one.
307 /// Returns an [`Err`] if `earlier` is later than `self`, and the error
308 /// contains how far from `self` the time is.
310 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
311 /// [`Duration`]: ../../std/time/struct.Duration.html
312 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
317 /// use std::time::SystemTime;
319 /// let sys_time = SystemTime::now();
320 /// let difference = sys_time.duration_since(sys_time)
321 /// .expect("SystemTime::duration_since failed");
322 /// println!("{:?}", difference);
324 #[stable(feature = "time2", since = "1.8.0")]
325 pub fn duration_since(&self, earlier: SystemTime)
326 -> Result<Duration, SystemTimeError> {
327 self.0.sub_time(&earlier.0).map_err(SystemTimeError)
330 /// Returns the amount of time elapsed since this system time was created.
332 /// This function may fail as the underlying system clock is susceptible to
333 /// drift and updates (e.g. the system clock could go backwards), so this
334 /// function may not always succeed. If successful, [`Ok`]`(`[`Duration`]`)` is
335 /// returned where the duration represents the amount of time elapsed from
336 /// this time measurement to the current time.
338 /// Returns an [`Err`] if `self` is later than the current system time, and
339 /// the error contains how far from the current system time `self` is.
341 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
342 /// [`Duration`]: ../../std/time/struct.Duration.html
343 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
348 /// use std::thread::sleep;
349 /// use std::time::{Duration, SystemTime};
351 /// let sys_time = SystemTime::now();
352 /// let one_sec = Duration::from_secs(1);
354 /// assert!(sys_time.elapsed().unwrap() >= one_sec);
356 #[stable(feature = "time2", since = "1.8.0")]
357 pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
358 SystemTime::now().duration_since(*self)
362 #[stable(feature = "time2", since = "1.8.0")]
363 impl Add<Duration> for SystemTime {
364 type Output = SystemTime;
366 fn add(self, dur: Duration) -> SystemTime {
367 SystemTime(self.0.add_duration(&dur))
371 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
372 impl AddAssign<Duration> for SystemTime {
373 fn add_assign(&mut self, other: Duration) {
374 *self = *self + other;
378 #[stable(feature = "time2", since = "1.8.0")]
379 impl Sub<Duration> for SystemTime {
380 type Output = SystemTime;
382 fn sub(self, dur: Duration) -> SystemTime {
383 SystemTime(self.0.sub_duration(&dur))
387 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
388 impl SubAssign<Duration> for SystemTime {
389 fn sub_assign(&mut self, other: Duration) {
390 *self = *self - other;
394 #[stable(feature = "time2", since = "1.8.0")]
395 impl fmt::Debug for SystemTime {
396 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
401 /// An anchor in time which can be used to create new `SystemTime` instances or
402 /// learn about where in time a `SystemTime` lies.
404 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
405 /// respect to the system clock. Using `duration_since` on an existing
406 /// [`SystemTime`] instance can tell how far away from this point in time a
407 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
408 /// [`SystemTime`] instance to represent another fixed point in time.
410 /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
415 /// use std::time::{SystemTime, UNIX_EPOCH};
417 /// match SystemTime::now().duration_since(UNIX_EPOCH) {
418 /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
419 /// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
422 #[stable(feature = "time2", since = "1.8.0")]
423 pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);
425 impl SystemTimeError {
426 /// Returns the positive duration which represents how far forward the
427 /// second system time was from the first.
429 /// A `SystemTimeError` is returned from the [`duration_since`] and [`elapsed`]
430 /// methods of [`SystemTime`] whenever the second system time represents a point later
431 /// in time than the `self` of the method call.
433 /// [`duration_since`]: ../../std/time/struct.SystemTime.html#method.duration_since
434 /// [`elapsed`]: ../../std/time/struct.SystemTime.html#method.elapsed
435 /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
440 /// use std::thread::sleep;
441 /// use std::time::{Duration, SystemTime};
443 /// let sys_time = SystemTime::now();
444 /// sleep(Duration::from_secs(1));
445 /// let new_sys_time = SystemTime::now();
446 /// match sys_time.duration_since(new_sys_time) {
448 /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
451 #[stable(feature = "time2", since = "1.8.0")]
452 pub fn duration(&self) -> Duration {
457 #[stable(feature = "time2", since = "1.8.0")]
458 impl Error for SystemTimeError {
459 fn description(&self) -> &str { "other time was not earlier than self" }
462 #[stable(feature = "time2", since = "1.8.0")]
463 impl fmt::Display for SystemTimeError {
464 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
465 write!(f, "second time provided was later than self")
469 impl FromInner<time::SystemTime> for SystemTime {
470 fn from_inner(time: time::SystemTime) -> SystemTime {
477 use super::{Instant, SystemTime, Duration, UNIX_EPOCH};
479 macro_rules! assert_almost_eq {
480 ($a:expr, $b:expr) => ({
481 let (a, b) = ($a, $b);
483 let (a, b) = if a > b {(a, b)} else {(b, a)};
484 assert!(a - Duration::new(0, 1000) <= b,
485 "{:?} is not almost equal to {:?}", a, b);
491 fn instant_monotonic() {
492 let a = Instant::now();
493 let b = Instant::now();
498 fn instant_elapsed() {
499 let a = Instant::now();
505 let a = Instant::now();
506 let b = Instant::now();
507 println!("a: {:?}", a);
508 println!("b: {:?}", b);
509 let dur = b.duration_since(a);
510 println!("dur: {:?}", dur);
511 assert_almost_eq!(b - dur, a);
512 assert_almost_eq!(a + dur, b);
514 let second = Duration::new(1, 0);
515 assert_almost_eq!(a - second + second, a);
520 fn instant_duration_panic() {
521 let a = Instant::now();
522 (a - Duration::new(1, 0)).duration_since(a);
526 fn system_time_math() {
527 let a = SystemTime::now();
528 let b = SystemTime::now();
529 match b.duration_since(a) {
530 Ok(dur) if dur == Duration::new(0, 0) => {
531 assert_almost_eq!(a, b);
535 assert_almost_eq!(b - dur, a);
536 assert_almost_eq!(a + dur, b);
539 let dur = dur.duration();
541 assert_almost_eq!(b + dur, a);
542 assert_almost_eq!(a - dur, b);
546 let second = Duration::new(1, 0);
547 assert_almost_eq!(a.duration_since(a - second).unwrap(), second);
548 assert_almost_eq!(a.duration_since(a + second).unwrap_err()
549 .duration(), second);
551 assert_almost_eq!(a - second + second, a);
553 // A difference of 80 and 800 years cannot fit inside a 32-bit time_t
554 if !(cfg!(unix) && ::mem::size_of::<::libc::time_t>() <= 4) {
555 let eighty_years = second * 60 * 60 * 24 * 365 * 80;
556 assert_almost_eq!(a - eighty_years + eighty_years, a);
557 assert_almost_eq!(a - (eighty_years * 10) + (eighty_years * 10), a);
560 let one_second_from_epoch = UNIX_EPOCH + Duration::new(1, 0);
561 let one_second_from_epoch2 = UNIX_EPOCH + Duration::new(0, 500_000_000)
562 + Duration::new(0, 500_000_000);
563 assert_eq!(one_second_from_epoch, one_second_from_epoch2);
567 fn system_time_elapsed() {
568 let a = SystemTime::now();
574 let ts = SystemTime::now();
575 let a = ts.duration_since(UNIX_EPOCH).unwrap();
576 let b = ts.duration_since(UNIX_EPOCH - Duration::new(1, 0)).unwrap();
578 assert_eq!(b - a, Duration::new(1, 0));
580 let thirty_years = Duration::new(1, 0) * 60 * 60 * 24 * 365 * 30;
582 // Right now for CI this test is run in an emulator, and apparently the
583 // aarch64 emulator's sense of time is that we're still living in the
586 // Otherwise let's assume that we're all running computers later than
588 if !cfg!(target_arch = "aarch64") {
589 assert!(a > thirty_years);
592 // let's assume that we're all running computers earlier than 2090.
593 // Should give us ~70 years to fix this!
594 let hundred_twenty_years = thirty_years * 4;
595 assert!(a < hundred_twenty_years);