Struct std::time::Instant 1.8.0[−][src]
pub struct Instant(_);
Expand description
单调非递减时钟的度量。
不透明且仅对 Duration
有用。
创建时始终保证瞬时不小于任何先前测量的瞬时,并且对于执行诸如测量基准或计时操作花费多长时间等任务通常很有用。
但是请注意,不能保证瞬间稳定。换句话说,底层时钟的每个滴答声的长度可能不同 (例如 几秒钟可能比其他更长)。瞬间可能会向前跳跃或经历时间膨胀 (减速或加速),但永远不会向后退。
即时消息是不透明的类型,只能相互比较。没有方法可以立即获取 “秒数”。 相反,它仅允许测量两个瞬间之间的持续时间 (或比较两个瞬间)。
Instant
结构体的大小可能会因目标操作系统而异。
Example:
use std::time::{Duration, Instant};
use std::thread::sleep;
fn main() {
let now = Instant::now();
// 我们睡了 2 秒钟
sleep(Duration::new(2, 0));
// 它打印 '2'
println!("{}", now.elapsed().as_secs());
}
Run特定于操作系统的行为
Instant
是系统特定类型的包装器,根据底层操作系统的不同,它的行为可能会有所不同。
例如,以下代码段在 Linux 上很好,但在 macOS 上为 panics:
use std::time::{Instant, Duration};
let now = Instant::now();
let max_nanoseconds = u64::MAX / 1_000_000_000;
let duration = Duration::new(max_nanoseconds, 0);
println!("{:?}", now + duration);
Run底层系统调用
当前,正在使用以下系统调用来使用 now()
获取当前时间:
Platform | System call |
---|---|
SGX | insecure_time usercall. More information on timekeeping in SGX |
UNIX | clock_gettime (Monotonic Clock) |
Darwin | mach_absolute_time |
VXWorks | clock_gettime (Monotonic Clock) |
SOLID | get_tim |
WASI | __wasi_clock_time_get (Monotonic Clock) |
Windows | QueryPerformanceCounter |
免责声明: 这些系统调用可能会随时间变化。
Note: 如果
add
的数学运算可能是 panic 结构体不能代表新的时间点。
Implementations
返回从另一个时刻到该时刻所经过的时间; 如果该时刻晚于该时刻,则返回 None。
Examples
use std::time::{Duration, Instant};
use std::thread::sleep;
let now = Instant::now();
sleep(Duration::new(1, 0));
let new_now = Instant::now();
println!("{:?}", new_now.checked_duration_since(now));
println!("{:?}", now.checked_duration_since(new_now)); // None
Run返回从另一时刻到该时刻所经过的时间,如果该时刻晚于该时刻,则返回零持续时间。
Examples
use std::time::{Duration, Instant};
use std::thread::sleep;
let now = Instant::now();
sleep(Duration::new(1, 0));
let new_now = Instant::now();
println!("{:?}", new_now.saturating_duration_since(now));
println!("{:?}", now.saturating_duration_since(new_now)); // 0ns
Run如果 t
可以表示为 Instant
(这意味着它在底层数据结构的边界内),则返回 Some(t)
,其中 t
是时间 self + duration
,否则返回 None
。
如果 t
可以表示为 Instant
(表示它在底层数据结构体的边界之内),则返回 Some(t)
,其中 t
是 self - duration
的时间,否则返回 None
。