1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
#![cfg_attr(feature = "rdtsc", feature(asm))]
#![deny(warnings)]
extern crate libc;
#[cfg(target_os = "windows")]
#[macro_use]
extern crate lazy_static;
#[cfg(target_os = "windows")]
extern crate winapi;
#[derive(Clone)]
pub struct Clocksource {
ref_id: Clock,
ref_t0: u64,
ref_hz: f64,
src_id: Clock,
src_t0: u64,
src_hz: f64,
}
const ONE_GHZ: f64 = 1_000_000_000.0;
#[derive(Clone, Debug, PartialEq)]
pub enum Clock {
Monotonic,
Realtime,
Counter,
}
fn read(clock: &Clock) -> u64 {
match *clock {
Clock::Monotonic => get_precise_ns(),
Clock::Realtime => get_unix_time(),
Clock::Counter => rdtsc(),
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn get_unix_time() -> u64 {
let mut ts = libc::timespec {
tv_sec: 0,
tv_nsec: 0,
};
unsafe {
libc::clock_gettime(libc::CLOCK_REALTIME, &mut ts);
}
(ts.tv_sec as u64) * 1_000_000_000 + (ts.tv_nsec as u64)
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn get_precise_ns() -> u64 {
unsafe {
let time = libc::mach_absolute_time();
let info = {
static mut INFO: libc::mach_timebase_info =
libc::mach_timebase_info { numer: 0, denom: 0 };
static ONCE: std::sync::Once = std::sync::ONCE_INIT;
ONCE.call_once(|| { libc::mach_timebase_info(&mut INFO); });
&INFO
};
time * info.numer as u64 / info.denom as u64
}
}
#[cfg(target_os = "windows")]
fn get_unix_time() -> u64 {
use std::mem;
use winapi::um::sysinfoapi;
use winapi::shared::minwindef::{FILETIME};
const OFFSET: u64 = 116_444_736_000_000_000;
let mut file_time = unsafe {
let mut file_time = mem::uninitialized();
sysinfoapi::GetSystemTimePreciseAsFileTime(&mut file_time);
(mem::transmute::<FILETIME,i64>(file_time)) as u64
};
file_time -= OFFSET;
file_time * 100
}
#[cfg(target_os = "windows")]
fn get_precise_ns() -> u64 {
use std::mem;
use winapi::um::winnt::LARGE_INTEGER;
use winapi::um::profileapi;
lazy_static! {
static ref PRF_FREQUENCY: u64 = {
unsafe {
let mut frq = mem::uninitialized();
let res = profileapi::QueryPerformanceFrequency(&mut frq);
debug_assert_ne!(res, 0, "Failed to query performance frequency, {}", res);
let frq = *frq.QuadPart() as u64;
frq
}
};
}
let cnt = unsafe {
let mut cnt = mem::uninitialized();
debug_assert_eq!(mem::align_of::<LARGE_INTEGER>(), 8);
let res = profileapi::QueryPerformanceCounter(&mut cnt);
debug_assert_ne!(res, 0, "Failed to query performance counter {}", res);
*cnt.QuadPart() as u64
};
let cnt = cnt as f64 / (*PRF_FREQUENCY as f64 / 1_000_000_000_f64);
cnt as u64
}
#[cfg(all(not(target_os = "macos"), not(target_os = "ios"), not(target_os = "windows")))]
fn get_unix_time() -> u64 {
let mut ts = libc::timespec {
tv_sec: 0,
tv_nsec: 0,
};
unsafe {
libc::clock_gettime(libc::CLOCK_REALTIME, &mut ts);
}
(ts.tv_sec as u64) * 1_000_000_000 + (ts.tv_nsec as u64)
}
#[cfg(all(not(target_os = "macos"), not(target_os = "ios"), not(target_os = "windows")))]
fn get_precise_ns() -> u64 {
let mut ts = libc::timespec {
tv_sec: 0,
tv_nsec: 0,
};
unsafe {
libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts);
}
(ts.tv_sec as u64) * 1_000_000_000 + (ts.tv_nsec as u64)
}
#[cfg(feature = "rdtsc")]
#[allow(unused_mut)]
fn rdtsc() -> u64 {
let mut l: u32;
let mut m: u32;
unsafe {
asm!("lfence; rdtsc" : "={eax}" (l), "={edx}" (m) ::: "volatile");
}
((m as u64) << 32) | (l as u64)
}
#[cfg(not(feature = "rdtsc"))]
fn rdtsc() -> u64 {
panic!("Clock::Counter requires 'rdtsc' feature");
}
impl Default for Clocksource {
fn default() -> Clocksource {
if cfg!(feature = "rdtsc") {
Clocksource::configured(Clock::Monotonic, Clock::Counter)
} else {
Clocksource::configured(Clock::Monotonic, Clock::Monotonic)
}
}
}
impl Clocksource {
pub fn new() -> Clocksource {
Default::default()
}
pub fn configured(reference: Clock, source: Clock) -> Clocksource {
let mut cs = Clocksource {
ref_id: reference,
ref_t0: 0,
ref_hz: ONE_GHZ,
src_id: source,
src_t0: 0,
src_hz: ONE_GHZ,
};
cs.calibrate();
cs
}
pub fn frequency(&self) -> f64 {
self.src_hz
}
pub fn counter(&self) -> u64 {
read(&self.src_id)
}
pub fn reference(&self) -> u64 {
read(&self.ref_id)
}
pub fn time(&self) -> u64 {
let raw = self.counter();
if self.src_id != self.ref_id {
self.convert(raw) as u64
} else {
raw
}
}
pub fn calibrate(&mut self) {
self.ref_t0 = self.reference();
self.src_t0 = self.counter();
let ref_t1 = self.ref_t0 + self.ref_hz as u64;
loop {
let t = self.reference();
if t >= ref_t1 {
break;
}
}
let src_t1 = self.counter();
let ref_d = ref_t1 - self.ref_t0;
let src_d = src_t1 - self.src_t0;
self.src_hz = src_d as f64 * self.ref_hz / ref_d as f64;
}
pub fn recalibrate(&mut self) {
let ref_t1 = self.reference();
let src_t1 = self.counter();
let ref_d = ref_t1.wrapping_sub(self.ref_t0);
let src_d = src_t1.wrapping_sub(self.src_t0);
self.src_hz = src_d as f64 * self.ref_hz / ref_d as f64;
}
pub fn phase_error(&self) -> f64 {
if self.src_id == self.ref_id {
return 0.0;
}
let ref_t1 = self.reference();
let src_t1 = self.time();
(src_t1 as i64 - ref_t1 as i64) as f64 / self.ref_hz
}
pub fn convert(&self, src_t1: u64) -> f64 {
(self.ref_hz * (src_t1.wrapping_sub(self.src_t0) as f64 / self.src_hz)) + self.ref_t0 as f64
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_raw() {
let cs = Clocksource::default();
let a = cs.counter();
let b = cs.counter();
assert!(b >= a);
}
#[test]
fn test_reference() {
let cs = Clocksource::default();
let a = cs.reference();
let b = cs.reference();
assert!(b >= a);
}
#[test]
fn test_source() {
let cs = Clocksource::default();
let ref_0 = cs.reference();
let src_0 = cs.time();
let dt = src_0 as f64 - ref_0 as f64;
let pe = cs.phase_error();
assert!(dt < 1000.0);
assert!(dt > -1000.0);
assert!(pe < 1000.0);
assert!(pe > -1000.0);
}
}