1 | //! Temporal quantification. |
2 | //! |
3 | //! # Examples |
4 | //! |
5 | //! There are multiple ways to create a new [`Duration`]: |
6 | //! |
7 | //! ``` |
8 | //! # use std::time::Duration; |
9 | //! let five_seconds = Duration::from_secs(5); |
10 | //! assert_eq!(five_seconds, Duration::from_millis(5_000)); |
11 | //! assert_eq!(five_seconds, Duration::from_micros(5_000_000)); |
12 | //! assert_eq!(five_seconds, Duration::from_nanos(5_000_000_000)); |
13 | //! |
14 | //! let ten_seconds = Duration::from_secs(10); |
15 | //! let seven_nanos = Duration::from_nanos(7); |
16 | //! let total = ten_seconds + seven_nanos; |
17 | //! assert_eq!(total, Duration::new(10, 7)); |
18 | //! ``` |
19 | //! |
20 | //! Using [`Instant`] to calculate how long a function took to run: |
21 | //! |
22 | //! ```ignore (incomplete) |
23 | //! let now = Instant::now(); |
24 | //! |
25 | //! // Calling a slow function, it may take a while |
26 | //! slow_function(); |
27 | //! |
28 | //! let elapsed_time = now.elapsed(); |
29 | //! println!("Running slow_function() took {} seconds." , elapsed_time.as_secs()); |
30 | //! ``` |
31 | |
32 | #![stable (feature = "time" , since = "1.3.0" )] |
33 | |
34 | #[stable (feature = "time" , since = "1.3.0" )] |
35 | pub use core::time::Duration; |
36 | #[stable (feature = "duration_checked_float" , since = "1.66.0" )] |
37 | pub use core::time::TryFromFloatSecsError; |
38 | |
39 | use crate::error::Error; |
40 | use crate::fmt; |
41 | use crate::ops::{Add, AddAssign, Sub, SubAssign}; |
42 | use crate::sys::time; |
43 | use crate::sys_common::{FromInner, IntoInner}; |
44 | |
45 | /// A measurement of a monotonically nondecreasing clock. |
46 | /// Opaque and useful only with [`Duration`]. |
47 | /// |
48 | /// Instants are always guaranteed, barring [platform bugs], to be no less than any previously |
49 | /// measured instant when created, and are often useful for tasks such as measuring |
50 | /// benchmarks or timing how long an operation takes. |
51 | /// |
52 | /// Note, however, that instants are **not** guaranteed to be **steady**. In other |
53 | /// words, each tick of the underlying clock might not be the same length (e.g. |
54 | /// some seconds may be longer than others). An instant may jump forwards or |
55 | /// experience time dilation (slow down or speed up), but it will never go |
56 | /// backwards. |
57 | /// As part of this non-guarantee it is also not specified whether system suspends count as |
58 | /// elapsed time or not. The behavior varies across platforms and Rust versions. |
59 | /// |
60 | /// Instants are opaque types that can only be compared to one another. There is |
61 | /// no method to get "the number of seconds" from an instant. Instead, it only |
62 | /// allows measuring the duration between two instants (or comparing two |
63 | /// instants). |
64 | /// |
65 | /// The size of an `Instant` struct may vary depending on the target operating |
66 | /// system. |
67 | /// |
68 | /// Example: |
69 | /// |
70 | /// ```no_run |
71 | /// use std::time::{Duration, Instant}; |
72 | /// use std::thread::sleep; |
73 | /// |
74 | /// fn main() { |
75 | /// let now = Instant::now(); |
76 | /// |
77 | /// // we sleep for 2 seconds |
78 | /// sleep(Duration::new(2, 0)); |
79 | /// // it prints '2' |
80 | /// println!("{}" , now.elapsed().as_secs()); |
81 | /// } |
82 | /// ``` |
83 | /// |
84 | /// [platform bugs]: Instant#monotonicity |
85 | /// |
86 | /// # OS-specific behaviors |
87 | /// |
88 | /// An `Instant` is a wrapper around system-specific types and it may behave |
89 | /// differently depending on the underlying operating system. For example, |
90 | /// the following snippet is fine on Linux but panics on macOS: |
91 | /// |
92 | /// ```no_run |
93 | /// use std::time::{Instant, Duration}; |
94 | /// |
95 | /// let now = Instant::now(); |
96 | /// let days_per_10_millennia = 365_2425; |
97 | /// let solar_seconds_per_day = 60 * 60 * 24; |
98 | /// let millenium_in_solar_seconds = 31_556_952_000; |
99 | /// assert_eq!(millenium_in_solar_seconds, days_per_10_millennia * solar_seconds_per_day / 10); |
100 | /// |
101 | /// let duration = Duration::new(millenium_in_solar_seconds, 0); |
102 | /// println!("{:?}" , now + duration); |
103 | /// ``` |
104 | /// |
105 | /// For cross-platform code, you can comfortably use durations of up to around one hundred years. |
106 | /// |
107 | /// # Underlying System calls |
108 | /// |
109 | /// The following system calls are [currently] being used by `now()` to find out |
110 | /// the current time: |
111 | /// |
112 | /// | Platform | System call | |
113 | /// |-----------|----------------------------------------------------------------------| |
114 | /// | SGX | [`insecure_time` usercall]. More information on [timekeeping in SGX] | |
115 | /// | UNIX | [clock_gettime (Monotonic Clock)] | |
116 | /// | Darwin | [clock_gettime (Monotonic Clock)] | |
117 | /// | VXWorks | [clock_gettime (Monotonic Clock)] | |
118 | /// | SOLID | `get_tim` | |
119 | /// | WASI | [__wasi_clock_time_get (Monotonic Clock)] | |
120 | /// | Windows | [QueryPerformanceCounter] | |
121 | /// |
122 | /// [currently]: crate::io#platform-specific-behavior |
123 | /// [QueryPerformanceCounter]: https://docs.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter |
124 | /// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time |
125 | /// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode |
126 | /// [__wasi_clock_time_get (Monotonic Clock)]: https://github.com/WebAssembly/WASI/blob/main/legacy/preview1/docs.md#clock_time_get |
127 | /// [clock_gettime (Monotonic Clock)]: https://linux.die.net/man/3/clock_gettime |
128 | /// |
129 | /// **Disclaimer:** These system calls might change over time. |
130 | /// |
131 | /// > Note: mathematical operations like [`add`] may panic if the underlying |
132 | /// > structure cannot represent the new point in time. |
133 | /// |
134 | /// [`add`]: Instant::add |
135 | /// |
136 | /// ## Monotonicity |
137 | /// |
138 | /// On all platforms `Instant` will try to use an OS API that guarantees monotonic behavior |
139 | /// if available, which is the case for all [tier 1] platforms. |
140 | /// In practice such guarantees are – under rare circumstances – broken by hardware, virtualization |
141 | /// or operating system bugs. To work around these bugs and platforms not offering monotonic clocks |
142 | /// [`duration_since`], [`elapsed`] and [`sub`] saturate to zero. In older Rust versions this |
143 | /// lead to a panic instead. [`checked_duration_since`] can be used to detect and handle situations |
144 | /// where monotonicity is violated, or `Instant`s are subtracted in the wrong order. |
145 | /// |
146 | /// This workaround obscures programming errors where earlier and later instants are accidentally |
147 | /// swapped. For this reason future Rust versions may reintroduce panics. |
148 | /// |
149 | /// [tier 1]: https://doc.rust-lang.org/rustc/platform-support.html |
150 | /// [`duration_since`]: Instant::duration_since |
151 | /// [`elapsed`]: Instant::elapsed |
152 | /// [`sub`]: Instant::sub |
153 | /// [`checked_duration_since`]: Instant::checked_duration_since |
154 | /// |
155 | #[derive (Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] |
156 | #[stable (feature = "time2" , since = "1.8.0" )] |
157 | #[cfg_attr (not(test), rustc_diagnostic_item = "Instant" )] |
158 | pub struct Instant(time::Instant); |
159 | |
160 | /// A measurement of the system clock, useful for talking to |
161 | /// external entities like the file system or other processes. |
162 | /// |
163 | /// Distinct from the [`Instant`] type, this time measurement **is not |
164 | /// monotonic**. This means that you can save a file to the file system, then |
165 | /// save another file to the file system, **and the second file has a |
166 | /// `SystemTime` measurement earlier than the first**. In other words, an |
167 | /// operation that happens after another operation in real time may have an |
168 | /// earlier `SystemTime`! |
169 | /// |
170 | /// Consequently, comparing two `SystemTime` instances to learn about the |
171 | /// duration between them returns a [`Result`] instead of an infallible [`Duration`] |
172 | /// to indicate that this sort of time drift may happen and needs to be handled. |
173 | /// |
174 | /// Although a `SystemTime` cannot be directly inspected, the [`UNIX_EPOCH`] |
175 | /// constant is provided in this module as an anchor in time to learn |
176 | /// information about a `SystemTime`. By calculating the duration from this |
177 | /// fixed point in time, a `SystemTime` can be converted to a human-readable time, |
178 | /// or perhaps some other string representation. |
179 | /// |
180 | /// The size of a `SystemTime` struct may vary depending on the target operating |
181 | /// system. |
182 | /// |
183 | /// A `SystemTime` does not count leap seconds. |
184 | /// `SystemTime::now()`'s behavior around a leap second |
185 | /// is the same as the operating system's wall clock. |
186 | /// The precise behavior near a leap second |
187 | /// (e.g. whether the clock appears to run slow or fast, or stop, or jump) |
188 | /// depends on platform and configuration, |
189 | /// so should not be relied on. |
190 | /// |
191 | /// Example: |
192 | /// |
193 | /// ```no_run |
194 | /// use std::time::{Duration, SystemTime}; |
195 | /// use std::thread::sleep; |
196 | /// |
197 | /// fn main() { |
198 | /// let now = SystemTime::now(); |
199 | /// |
200 | /// // we sleep for 2 seconds |
201 | /// sleep(Duration::new(2, 0)); |
202 | /// match now.elapsed() { |
203 | /// Ok(elapsed) => { |
204 | /// // it prints '2' |
205 | /// println!("{}" , elapsed.as_secs()); |
206 | /// } |
207 | /// Err(e) => { |
208 | /// // the system clock went backwards! |
209 | /// println!("Great Scott! {e:?}" ); |
210 | /// } |
211 | /// } |
212 | /// } |
213 | /// ``` |
214 | /// |
215 | /// # Platform-specific behavior |
216 | /// |
217 | /// The precision of `SystemTime` can depend on the underlying OS-specific time format. |
218 | /// For example, on Windows the time is represented in 100 nanosecond intervals whereas Linux |
219 | /// can represent nanosecond intervals. |
220 | /// |
221 | /// The following system calls are [currently] being used by `now()` to find out |
222 | /// the current time: |
223 | /// |
224 | /// | Platform | System call | |
225 | /// |-----------|----------------------------------------------------------------------| |
226 | /// | SGX | [`insecure_time` usercall]. More information on [timekeeping in SGX] | |
227 | /// | UNIX | [clock_gettime (Realtime Clock)] | |
228 | /// | Darwin | [clock_gettime (Realtime Clock)] | |
229 | /// | VXWorks | [clock_gettime (Realtime Clock)] | |
230 | /// | SOLID | `SOLID_RTC_ReadTime` | |
231 | /// | WASI | [__wasi_clock_time_get (Realtime Clock)] | |
232 | /// | Windows | [GetSystemTimePreciseAsFileTime] / [GetSystemTimeAsFileTime] | |
233 | /// |
234 | /// [currently]: crate::io#platform-specific-behavior |
235 | /// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time |
236 | /// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode |
237 | /// [clock_gettime (Realtime Clock)]: https://linux.die.net/man/3/clock_gettime |
238 | /// [__wasi_clock_time_get (Realtime Clock)]: https://github.com/WebAssembly/WASI/blob/main/legacy/preview1/docs.md#clock_time_get |
239 | /// [GetSystemTimePreciseAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimepreciseasfiletime |
240 | /// [GetSystemTimeAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimeasfiletime |
241 | /// |
242 | /// **Disclaimer:** These system calls might change over time. |
243 | /// |
244 | /// > Note: mathematical operations like [`add`] may panic if the underlying |
245 | /// > structure cannot represent the new point in time. |
246 | /// |
247 | /// [`add`]: SystemTime::add |
248 | /// [`UNIX_EPOCH`]: SystemTime::UNIX_EPOCH |
249 | #[derive (Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] |
250 | #[stable (feature = "time2" , since = "1.8.0" )] |
251 | pub struct SystemTime(time::SystemTime); |
252 | |
253 | /// An error returned from the `duration_since` and `elapsed` methods on |
254 | /// `SystemTime`, used to learn how far in the opposite direction a system time |
255 | /// lies. |
256 | /// |
257 | /// # Examples |
258 | /// |
259 | /// ```no_run |
260 | /// use std::thread::sleep; |
261 | /// use std::time::{Duration, SystemTime}; |
262 | /// |
263 | /// let sys_time = SystemTime::now(); |
264 | /// sleep(Duration::from_secs(1)); |
265 | /// let new_sys_time = SystemTime::now(); |
266 | /// match sys_time.duration_since(new_sys_time) { |
267 | /// Ok(_) => {} |
268 | /// Err(e) => println!("SystemTimeError difference: {:?}" , e.duration()), |
269 | /// } |
270 | /// ``` |
271 | #[derive (Clone, Debug)] |
272 | #[stable (feature = "time2" , since = "1.8.0" )] |
273 | pub struct SystemTimeError(Duration); |
274 | |
275 | impl Instant { |
276 | /// Returns an instant corresponding to "now". |
277 | /// |
278 | /// # Examples |
279 | /// |
280 | /// ``` |
281 | /// use std::time::Instant; |
282 | /// |
283 | /// let now = Instant::now(); |
284 | /// ``` |
285 | #[must_use ] |
286 | #[stable (feature = "time2" , since = "1.8.0" )] |
287 | #[cfg_attr (not(test), rustc_diagnostic_item = "instant_now" )] |
288 | pub fn now() -> Instant { |
289 | Instant(time::Instant::now()) |
290 | } |
291 | |
292 | /// Returns the amount of time elapsed from another instant to this one, |
293 | /// or zero duration if that instant is later than this one. |
294 | /// |
295 | /// # Panics |
296 | /// |
297 | /// Previous Rust versions panicked when `earlier` was later than `self`. Currently this |
298 | /// method saturates. Future versions may reintroduce the panic in some circumstances. |
299 | /// See [Monotonicity]. |
300 | /// |
301 | /// [Monotonicity]: Instant#monotonicity |
302 | /// |
303 | /// # Examples |
304 | /// |
305 | /// ```no_run |
306 | /// use std::time::{Duration, Instant}; |
307 | /// use std::thread::sleep; |
308 | /// |
309 | /// let now = Instant::now(); |
310 | /// sleep(Duration::new(1, 0)); |
311 | /// let new_now = Instant::now(); |
312 | /// println!("{:?}" , new_now.duration_since(now)); |
313 | /// println!("{:?}" , now.duration_since(new_now)); // 0ns |
314 | /// ``` |
315 | #[must_use ] |
316 | #[stable (feature = "time2" , since = "1.8.0" )] |
317 | pub fn duration_since(&self, earlier: Instant) -> Duration { |
318 | self.checked_duration_since(earlier).unwrap_or_default() |
319 | } |
320 | |
321 | /// Returns the amount of time elapsed from another instant to this one, |
322 | /// or None if that instant is later than this one. |
323 | /// |
324 | /// Due to [monotonicity bugs], even under correct logical ordering of the passed `Instant`s, |
325 | /// this method can return `None`. |
326 | /// |
327 | /// [monotonicity bugs]: Instant#monotonicity |
328 | /// |
329 | /// # Examples |
330 | /// |
331 | /// ```no_run |
332 | /// use std::time::{Duration, Instant}; |
333 | /// use std::thread::sleep; |
334 | /// |
335 | /// let now = Instant::now(); |
336 | /// sleep(Duration::new(1, 0)); |
337 | /// let new_now = Instant::now(); |
338 | /// println!("{:?}" , new_now.checked_duration_since(now)); |
339 | /// println!("{:?}" , now.checked_duration_since(new_now)); // None |
340 | /// ``` |
341 | #[must_use ] |
342 | #[stable (feature = "checked_duration_since" , since = "1.39.0" )] |
343 | pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> { |
344 | self.0.checked_sub_instant(&earlier.0) |
345 | } |
346 | |
347 | /// Returns the amount of time elapsed from another instant to this one, |
348 | /// or zero duration if that instant is later than this one. |
349 | /// |
350 | /// # Examples |
351 | /// |
352 | /// ```no_run |
353 | /// use std::time::{Duration, Instant}; |
354 | /// use std::thread::sleep; |
355 | /// |
356 | /// let now = Instant::now(); |
357 | /// sleep(Duration::new(1, 0)); |
358 | /// let new_now = Instant::now(); |
359 | /// println!("{:?}" , new_now.saturating_duration_since(now)); |
360 | /// println!("{:?}" , now.saturating_duration_since(new_now)); // 0ns |
361 | /// ``` |
362 | #[must_use ] |
363 | #[stable (feature = "checked_duration_since" , since = "1.39.0" )] |
364 | pub fn saturating_duration_since(&self, earlier: Instant) -> Duration { |
365 | self.checked_duration_since(earlier).unwrap_or_default() |
366 | } |
367 | |
368 | /// Returns the amount of time elapsed since this instant. |
369 | /// |
370 | /// # Panics |
371 | /// |
372 | /// Previous Rust versions panicked when the current time was earlier than self. Currently this |
373 | /// method returns a Duration of zero in that case. Future versions may reintroduce the panic. |
374 | /// See [Monotonicity]. |
375 | /// |
376 | /// [Monotonicity]: Instant#monotonicity |
377 | /// |
378 | /// # Examples |
379 | /// |
380 | /// ```no_run |
381 | /// use std::thread::sleep; |
382 | /// use std::time::{Duration, Instant}; |
383 | /// |
384 | /// let instant = Instant::now(); |
385 | /// let three_secs = Duration::from_secs(3); |
386 | /// sleep(three_secs); |
387 | /// assert!(instant.elapsed() >= three_secs); |
388 | /// ``` |
389 | #[must_use ] |
390 | #[stable (feature = "time2" , since = "1.8.0" )] |
391 | pub fn elapsed(&self) -> Duration { |
392 | Instant::now() - *self |
393 | } |
394 | |
395 | /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as |
396 | /// `Instant` (which means it's inside the bounds of the underlying data structure), `None` |
397 | /// otherwise. |
398 | #[stable (feature = "time_checked_add" , since = "1.34.0" )] |
399 | pub fn checked_add(&self, duration: Duration) -> Option<Instant> { |
400 | self.0.checked_add_duration(&duration).map(Instant) |
401 | } |
402 | |
403 | /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as |
404 | /// `Instant` (which means it's inside the bounds of the underlying data structure), `None` |
405 | /// otherwise. |
406 | #[stable (feature = "time_checked_add" , since = "1.34.0" )] |
407 | pub fn checked_sub(&self, duration: Duration) -> Option<Instant> { |
408 | self.0.checked_sub_duration(&duration).map(Instant) |
409 | } |
410 | } |
411 | |
412 | #[stable (feature = "time2" , since = "1.8.0" )] |
413 | impl Add<Duration> for Instant { |
414 | type Output = Instant; |
415 | |
416 | /// # Panics |
417 | /// |
418 | /// This function may panic if the resulting point in time cannot be represented by the |
419 | /// underlying data structure. See [`Instant::checked_add`] for a version without panic. |
420 | fn add(self, other: Duration) -> Instant { |
421 | self.checked_add(other).expect(msg:"overflow when adding duration to instant" ) |
422 | } |
423 | } |
424 | |
425 | #[stable (feature = "time_augmented_assignment" , since = "1.9.0" )] |
426 | impl AddAssign<Duration> for Instant { |
427 | fn add_assign(&mut self, other: Duration) { |
428 | *self = *self + other; |
429 | } |
430 | } |
431 | |
432 | #[stable (feature = "time2" , since = "1.8.0" )] |
433 | impl Sub<Duration> for Instant { |
434 | type Output = Instant; |
435 | |
436 | fn sub(self, other: Duration) -> Instant { |
437 | self.checked_sub(other).expect(msg:"overflow when subtracting duration from instant" ) |
438 | } |
439 | } |
440 | |
441 | #[stable (feature = "time_augmented_assignment" , since = "1.9.0" )] |
442 | impl SubAssign<Duration> for Instant { |
443 | fn sub_assign(&mut self, other: Duration) { |
444 | *self = *self - other; |
445 | } |
446 | } |
447 | |
448 | #[stable (feature = "time2" , since = "1.8.0" )] |
449 | impl Sub<Instant> for Instant { |
450 | type Output = Duration; |
451 | |
452 | /// Returns the amount of time elapsed from another instant to this one, |
453 | /// or zero duration if that instant is later than this one. |
454 | /// |
455 | /// # Panics |
456 | /// |
457 | /// Previous Rust versions panicked when `other` was later than `self`. Currently this |
458 | /// method saturates. Future versions may reintroduce the panic in some circumstances. |
459 | /// See [Monotonicity]. |
460 | /// |
461 | /// [Monotonicity]: Instant#monotonicity |
462 | fn sub(self, other: Instant) -> Duration { |
463 | self.duration_since(earlier:other) |
464 | } |
465 | } |
466 | |
467 | #[stable (feature = "time2" , since = "1.8.0" )] |
468 | impl fmt::Debug for Instant { |
469 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
470 | self.0.fmt(f) |
471 | } |
472 | } |
473 | |
474 | impl SystemTime { |
475 | /// An anchor in time which can be used to create new `SystemTime` instances or |
476 | /// learn about where in time a `SystemTime` lies. |
477 | // |
478 | // NOTE! this documentation is duplicated, here and in std::time::UNIX_EPOCH. |
479 | // The two copies are not quite identical, because of the difference in naming. |
480 | /// |
481 | /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with |
482 | /// respect to the system clock. Using `duration_since` on an existing |
483 | /// `SystemTime` instance can tell how far away from this point in time a |
484 | /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a |
485 | /// `SystemTime` instance to represent another fixed point in time. |
486 | /// |
487 | /// `duration_since(UNIX_EPOCH).unwrap().as_secs()` returns |
488 | /// the number of non-leap seconds since the start of 1970 UTC. |
489 | /// This is a POSIX `time_t` (as a `u64`), |
490 | /// and is the same time representation as used in many Internet protocols. |
491 | /// |
492 | /// # Examples |
493 | /// |
494 | /// ```no_run |
495 | /// use std::time::SystemTime; |
496 | /// |
497 | /// match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) { |
498 | /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!" , n.as_secs()), |
499 | /// Err(_) => panic!("SystemTime before UNIX EPOCH!" ), |
500 | /// } |
501 | /// ``` |
502 | #[stable (feature = "assoc_unix_epoch" , since = "1.28.0" )] |
503 | pub const UNIX_EPOCH: SystemTime = UNIX_EPOCH; |
504 | |
505 | /// Returns the system time corresponding to "now". |
506 | /// |
507 | /// # Examples |
508 | /// |
509 | /// ``` |
510 | /// use std::time::SystemTime; |
511 | /// |
512 | /// let sys_time = SystemTime::now(); |
513 | /// ``` |
514 | #[must_use ] |
515 | #[stable (feature = "time2" , since = "1.8.0" )] |
516 | pub fn now() -> SystemTime { |
517 | SystemTime(time::SystemTime::now()) |
518 | } |
519 | |
520 | /// Returns the amount of time elapsed from an earlier point in time. |
521 | /// |
522 | /// This function may fail because measurements taken earlier are not |
523 | /// guaranteed to always be before later measurements (due to anomalies such |
524 | /// as the system clock being adjusted either forwards or backwards). |
525 | /// [`Instant`] can be used to measure elapsed time without this risk of failure. |
526 | /// |
527 | /// If successful, <code>[Ok]\([Duration])</code> is returned where the duration represents |
528 | /// the amount of time elapsed from the specified measurement to this one. |
529 | /// |
530 | /// Returns an [`Err`] if `earlier` is later than `self`, and the error |
531 | /// contains how far from `self` the time is. |
532 | /// |
533 | /// # Examples |
534 | /// |
535 | /// ```no_run |
536 | /// use std::time::SystemTime; |
537 | /// |
538 | /// let sys_time = SystemTime::now(); |
539 | /// let new_sys_time = SystemTime::now(); |
540 | /// let difference = new_sys_time.duration_since(sys_time) |
541 | /// .expect("Clock may have gone backwards" ); |
542 | /// println!("{difference:?}" ); |
543 | /// ``` |
544 | #[stable (feature = "time2" , since = "1.8.0" )] |
545 | pub fn duration_since(&self, earlier: SystemTime) -> Result<Duration, SystemTimeError> { |
546 | self.0.sub_time(&earlier.0).map_err(SystemTimeError) |
547 | } |
548 | |
549 | /// Returns the difference from this system time to the |
550 | /// current clock time. |
551 | /// |
552 | /// This function may fail as the underlying system clock is susceptible to |
553 | /// drift and updates (e.g., the system clock could go backwards), so this |
554 | /// function might not always succeed. If successful, <code>[Ok]\([Duration])</code> is |
555 | /// returned where the duration represents the amount of time elapsed from |
556 | /// this time measurement to the current time. |
557 | /// |
558 | /// To measure elapsed time reliably, use [`Instant`] instead. |
559 | /// |
560 | /// Returns an [`Err`] if `self` is later than the current system time, and |
561 | /// the error contains how far from the current system time `self` is. |
562 | /// |
563 | /// # Examples |
564 | /// |
565 | /// ```no_run |
566 | /// use std::thread::sleep; |
567 | /// use std::time::{Duration, SystemTime}; |
568 | /// |
569 | /// let sys_time = SystemTime::now(); |
570 | /// let one_sec = Duration::from_secs(1); |
571 | /// sleep(one_sec); |
572 | /// assert!(sys_time.elapsed().unwrap() >= one_sec); |
573 | /// ``` |
574 | #[stable (feature = "time2" , since = "1.8.0" )] |
575 | pub fn elapsed(&self) -> Result<Duration, SystemTimeError> { |
576 | SystemTime::now().duration_since(*self) |
577 | } |
578 | |
579 | /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as |
580 | /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None` |
581 | /// otherwise. |
582 | #[stable (feature = "time_checked_add" , since = "1.34.0" )] |
583 | pub fn checked_add(&self, duration: Duration) -> Option<SystemTime> { |
584 | self.0.checked_add_duration(&duration).map(SystemTime) |
585 | } |
586 | |
587 | /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as |
588 | /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None` |
589 | /// otherwise. |
590 | #[stable (feature = "time_checked_add" , since = "1.34.0" )] |
591 | pub fn checked_sub(&self, duration: Duration) -> Option<SystemTime> { |
592 | self.0.checked_sub_duration(&duration).map(SystemTime) |
593 | } |
594 | } |
595 | |
596 | #[stable (feature = "time2" , since = "1.8.0" )] |
597 | impl Add<Duration> for SystemTime { |
598 | type Output = SystemTime; |
599 | |
600 | /// # Panics |
601 | /// |
602 | /// This function may panic if the resulting point in time cannot be represented by the |
603 | /// underlying data structure. See [`SystemTime::checked_add`] for a version without panic. |
604 | fn add(self, dur: Duration) -> SystemTime { |
605 | self.checked_add(dur).expect(msg:"overflow when adding duration to instant" ) |
606 | } |
607 | } |
608 | |
609 | #[stable (feature = "time_augmented_assignment" , since = "1.9.0" )] |
610 | impl AddAssign<Duration> for SystemTime { |
611 | fn add_assign(&mut self, other: Duration) { |
612 | *self = *self + other; |
613 | } |
614 | } |
615 | |
616 | #[stable (feature = "time2" , since = "1.8.0" )] |
617 | impl Sub<Duration> for SystemTime { |
618 | type Output = SystemTime; |
619 | |
620 | fn sub(self, dur: Duration) -> SystemTime { |
621 | self.checked_sub(dur).expect(msg:"overflow when subtracting duration from instant" ) |
622 | } |
623 | } |
624 | |
625 | #[stable (feature = "time_augmented_assignment" , since = "1.9.0" )] |
626 | impl SubAssign<Duration> for SystemTime { |
627 | fn sub_assign(&mut self, other: Duration) { |
628 | *self = *self - other; |
629 | } |
630 | } |
631 | |
632 | #[stable (feature = "time2" , since = "1.8.0" )] |
633 | impl fmt::Debug for SystemTime { |
634 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
635 | self.0.fmt(f) |
636 | } |
637 | } |
638 | |
639 | /// An anchor in time which can be used to create new `SystemTime` instances or |
640 | /// learn about where in time a `SystemTime` lies. |
641 | // |
642 | // NOTE! this documentation is duplicated, here and in SystemTime::UNIX_EPOCH. |
643 | // The two copies are not quite identical, because of the difference in naming. |
644 | /// |
645 | /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with |
646 | /// respect to the system clock. Using `duration_since` on an existing |
647 | /// [`SystemTime`] instance can tell how far away from this point in time a |
648 | /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a |
649 | /// [`SystemTime`] instance to represent another fixed point in time. |
650 | /// |
651 | /// `duration_since(UNIX_EPOCH).unwrap().as_secs()` returns |
652 | /// the number of non-leap seconds since the start of 1970 UTC. |
653 | /// This is a POSIX `time_t` (as a `u64`), |
654 | /// and is the same time representation as used in many Internet protocols. |
655 | /// |
656 | /// # Examples |
657 | /// |
658 | /// ```no_run |
659 | /// use std::time::{SystemTime, UNIX_EPOCH}; |
660 | /// |
661 | /// match SystemTime::now().duration_since(UNIX_EPOCH) { |
662 | /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!" , n.as_secs()), |
663 | /// Err(_) => panic!("SystemTime before UNIX EPOCH!" ), |
664 | /// } |
665 | /// ``` |
666 | #[stable (feature = "time2" , since = "1.8.0" )] |
667 | pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH); |
668 | |
669 | impl SystemTimeError { |
670 | /// Returns the positive duration which represents how far forward the |
671 | /// second system time was from the first. |
672 | /// |
673 | /// A `SystemTimeError` is returned from the [`SystemTime::duration_since`] |
674 | /// and [`SystemTime::elapsed`] methods whenever the second system time |
675 | /// represents a point later in time than the `self` of the method call. |
676 | /// |
677 | /// # Examples |
678 | /// |
679 | /// ```no_run |
680 | /// use std::thread::sleep; |
681 | /// use std::time::{Duration, SystemTime}; |
682 | /// |
683 | /// let sys_time = SystemTime::now(); |
684 | /// sleep(Duration::from_secs(1)); |
685 | /// let new_sys_time = SystemTime::now(); |
686 | /// match sys_time.duration_since(new_sys_time) { |
687 | /// Ok(_) => {} |
688 | /// Err(e) => println!("SystemTimeError difference: {:?}" , e.duration()), |
689 | /// } |
690 | /// ``` |
691 | #[must_use ] |
692 | #[stable (feature = "time2" , since = "1.8.0" )] |
693 | pub fn duration(&self) -> Duration { |
694 | self.0 |
695 | } |
696 | } |
697 | |
698 | #[stable (feature = "time2" , since = "1.8.0" )] |
699 | impl Error for SystemTimeError { |
700 | #[allow (deprecated)] |
701 | fn description(&self) -> &str { |
702 | "other time was not earlier than self" |
703 | } |
704 | } |
705 | |
706 | #[stable (feature = "time2" , since = "1.8.0" )] |
707 | impl fmt::Display for SystemTimeError { |
708 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
709 | write!(f, "second time provided was later than self" ) |
710 | } |
711 | } |
712 | |
713 | impl FromInner<time::SystemTime> for SystemTime { |
714 | fn from_inner(time: time::SystemTime) -> SystemTime { |
715 | SystemTime(time) |
716 | } |
717 | } |
718 | |
719 | impl IntoInner<time::SystemTime> for SystemTime { |
720 | fn into_inner(self) -> time::SystemTime { |
721 | self.0 |
722 | } |
723 | } |
724 | |