1个不稳定版本
0.1.0 | 2022年8月31日 |
---|
#8 in #measure-time
每月46次下载
11KB
148 行
adjusting_clock - 平滑调整时钟漂移
一个Rust包,用于测量时间,同时与外部源同步,例如调整客户端的时钟以匹配服务器之一的时间。
Clock
结构体作为一个计时器工作。在创建其实例后,您可以查询自开始以来经过的时间。时钟返回这个值作为std::time::Duration
。
use adjusting_clock::{Clock, ConstantRate};
use std::time::Instant;
let clock = Clock::new(Instant::now(), ConstantRate(0.001));
// ... after a while:
let current = clock.elapsed(Instant::now());
Clock
的有用之处在于其能够平滑调整当前时间以匹配另一个源的时间
use std::thread;
use adjusting_clock::{Clock, ConstantRate};
use std::time::{Instant, Duration};
// Create a clock that adjusts at a speed of 10 ms per second:
let t0 = Instant::now();
let mut clock = Clock::new(t0, ConstantRate(0.01));
// Request the current time to be 10 ms.
// As the clock just started at 0, this is an adjustment of +10 ms from the current time:
clock.set_target(t0, Duration::from_millis(10));
// After taking time to adjust at a rate of 10 ms per second,
// the current time will have been adjusted:
thread::sleep(Duration::from_millis(1000));
let elapsed = clock.elapsed(Instant::now());
//assert_eq!(elapsed, Duration::from_millis(1010)); // approx.
println!("Current time: {0} ms", elapsed.as_millis());
// Will print approximately 1010 ms, which is the sum of
// 10 because that's what the `set_target` call requested,
// and 1000 because that's how long time has passed since then.
请参阅测试用例以获取更多示例。