Struct SystemTime
struct SystemTime(_)
A measurement of the system clock, useful for talking to external entities like the file system or other processes.
Distinct from the Instant type, this time measurement is not
monotonic. This means that you can save a file to the file system, then
save another file to the file system, and the second file has a
SystemTime measurement earlier than the first. In other words, an
operation that happens after another operation in real time may have an
earlier SystemTime!
Consequently, comparing two SystemTime instances to learn about the
duration between them returns a Result instead of an infallible Duration
to indicate that this sort of time drift may happen and needs to be handled.
Although a SystemTime cannot be directly inspected, the UNIX_EPOCH
constant is provided in this module as an anchor in time to learn
information about a SystemTime. By calculating the duration from this
fixed point in time, a SystemTime can be converted to a human-readable time,
or perhaps some other string representation.
The size of a SystemTime struct may vary depending on the target operating
system.
A SystemTime does not count leap seconds.
SystemTime::now()'s behavior around a leap second
is the same as the operating system's wall clock.
The precise behavior near a leap second
(e.g. whether the clock appears to run slow or fast, or stop, or jump)
depends on platform and configuration,
so should not be relied on.
Example:
use std::time::{Duration, SystemTime};
use std::thread::sleep;
fn main() {
let now = SystemTime::now();
// we sleep for 2 seconds
sleep(Duration::new(2, 0));
match now.elapsed() {
Ok(elapsed) => {
// it prints '2'
println!("{}", elapsed.as_secs());
}
Err(e) => {
// the system clock went backwards!
println!("Great Scott! {e:?}");
}
}
}
Platform-specific behavior
The precision of SystemTime can depend on the underlying OS-specific time format.
For example, on Windows the time is represented in 100 nanosecond intervals whereas Linux
can represent nanosecond intervals.
The following system calls are currently being used by now() to find out
the current time:
| Platform | System call |
|---|---|
| SGX | insecure_time usercall. More information on timekeeping in SGX |
| UNIX | clock_gettime (Realtime Clock) |
| Darwin | clock_gettime (Realtime Clock) |
| VXWorks | clock_gettime (Realtime Clock) |
| SOLID | SOLID_RTC_ReadTime |
| WASI | __wasi_clock_time_get (Realtime Clock) |
| Windows | GetSystemTimePreciseAsFileTime / GetSystemTimeAsFileTime |
Disclaimer: These system calls might change over time.
Note: mathematical operations like
addmay panic if the underlying structure cannot represent the new point in time.
Implementations
impl SystemTime
fn now() -> SystemTimeReturns the system time corresponding to "now".
Examples
use SystemTime; let sys_time = now;fn duration_since(self: &Self, earlier: SystemTime) -> Result<Duration, SystemTimeError>Returns the amount of time elapsed from an earlier point in time.
This function may fail because measurements taken earlier are not guaranteed to always be before later measurements (due to anomalies such as the system clock being adjusted either forwards or backwards).
Instantcan be used to measure elapsed time without this risk of failure.If successful,
[Ok]([Duration])is returned where the duration represents the amount of time elapsed from the specified measurement to this one.Returns an
Errifearlieris later thanself, and the error contains how far fromselfthe time is.Examples
use std::time::SystemTime; let sys_time = SystemTime::now(); let new_sys_time = SystemTime::now(); let difference = new_sys_time.duration_since(sys_time) .expect("Clock may have gone backwards"); println!("{difference:?}");fn elapsed(self: &Self) -> Result<Duration, SystemTimeError>Returns the difference from this system time to the current clock time.
This function may fail as the underlying system clock is susceptible to drift and updates (e.g., the system clock could go backwards), so this function might not always succeed. If successful,
[Ok]([Duration])is returned where the duration represents the amount of time elapsed from this time measurement to the current time.To measure elapsed time reliably, use
Instantinstead.Returns an
Errifselfis later than the current system time, and the error contains how far from the current system timeselfis.Examples
use std::thread::sleep; use std::time::{Duration, SystemTime}; let sys_time = SystemTime::now(); let one_sec = Duration::from_secs(1); sleep(one_sec); assert!(sys_time.elapsed().unwrap() >= one_sec);fn checked_add(self: &Self, duration: Duration) -> Option<SystemTime>Returns
Some(t)wheretis the timeself + durationiftcan be represented asSystemTime(which means it's inside the bounds of the underlying data structure),Noneotherwise.In the case that the
durationis smaller than the time precision of the operating system,Some(self)will be returned.fn checked_sub(self: &Self, duration: Duration) -> Option<SystemTime>Returns
Some(t)wheretis the timeself - durationiftcan be represented asSystemTime(which means it's inside the bounds of the underlying data structure),Noneotherwise.In the case that the
durationis smaller than the time precision of the operating system,Some(self)will be returned.
impl Add for SystemTime
fn add(self: Self, dur: Duration) -> SystemTimePanics
This function may panic if the resulting point in time cannot be represented by the underlying data structure. See
SystemTime::checked_addfor a version without panic.
impl AddAssign for SystemTime
fn add_assign(self: &mut Self, other: Duration)
impl Clone for SystemTime
fn clone(self: &Self) -> SystemTime
impl Copy for SystemTime
impl Debug for SystemTime
fn fmt(self: &Self, f: &mut fmt::Formatter<'_>) -> fmt::Result
impl Eq for SystemTime
impl Freeze for SystemTime
impl Hash for SystemTime
fn hash<__H: $crate::hash::Hasher>(self: &Self, state: &mut __H)
impl Ord for SystemTime
fn cmp(self: &Self, other: &SystemTime) -> $crate::cmp::Ordering
impl PartialEq for SystemTime
fn eq(self: &Self, other: &SystemTime) -> bool
impl PartialOrd for SystemTime
fn partial_cmp(self: &Self, other: &SystemTime) -> $crate::option::Option<$crate::cmp::Ordering>
impl RefUnwindSafe for SystemTime
impl Send for SystemTime
impl StructuralPartialEq for SystemTime
impl Sub for SystemTime
fn sub(self: Self, dur: Duration) -> SystemTime
impl SubAssign for SystemTime
fn sub_assign(self: &mut Self, other: Duration)
impl Sync for SystemTime
impl Unpin for SystemTime
impl UnwindSafe for SystemTime
impl<T> Any for SystemTime
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for SystemTime
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for SystemTime
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> CloneToUninit for SystemTime
unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)
impl<T> From for SystemTime
fn from(t: T) -> TReturns the argument unchanged.
impl<T> ToOwned for SystemTime
fn to_owned(self: &Self) -> Tfn clone_into(self: &Self, target: &mut T)
impl<T, U> Into for SystemTime
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for SystemTime
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for SystemTime
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>