时间与定时器
学习目标
- 掌握
Instant 和 Duration
- 掌握时间测量
- 理解 SystemTime
核心概念
Instant(单调时钟)
use std::time::{Instant, Duration};
use std::thread;
fn main() {
let start = Instant::now();
thread::sleep(Duration::from_millis(100));
let elapsed = start.elapsed();
println!("耗时: {:?}", elapsed);
let d1 = Duration::from_secs(1);
let d2 = Duration::from_millis(500);
let total = d1 + d2;
println!("总时长: {:?}", total);
}
SystemTime(墙钟)
use std::time::SystemTime;
fn main() {
let now = SystemTime::now();
println!("当前时间: {:?}", now);
let duration = now.duration_since(SystemTime::UNIX_EPOCH).unwrap();
println!("Unix 时间戳: {} 秒", duration.as_secs());
}
基准测试
use std::time::Instant;
fn fibonacci(n: u64) -> u64 {
match n {
0 => 0,
1 => 1,
_ => fibonacci(n - 1) + fibonacci(n - 2),
}
}
fn main() {
let start = Instant::now();
let result = fibonacci(30);
let elapsed = start.elapsed();
println!("fibonacci(30) = {}, 耗时: {:?}", result, elapsed);
}
定时器循环
use std::time::{Instant, Duration};
fn main() {
let interval = Duration::from_secs(1);
let mut last = Instant::now();
for i in 0..5 {
while last.elapsed() < interval {
std::thread::yield_now();
}
println!("tick {}", i);
last = Instant::now();
}
}
小结
| 类型 | 用途 |
|---|
Instant | 单调时钟,测量耗时 |
SystemTime | 墙钟,获取当前时间 |
Duration | 时间间隔 |
elapsed() | 测量经过时间 |