eutils_rs/
timestamp.rs

1/// https://linux.die.net/man/3/clock_gettime
2
3/// Monotonically increasing timestamp, incremented by 1 when the clock interrupt 
4/// is triggered. This clock source is used by the bpf_ktime_get_ns function.
5pub fn current_monotime() -> u64 {
6    let mut ts = libc::timespec {
7        tv_sec: 0,
8        tv_nsec: 0,
9    };
10    unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts) };
11
12    (ts.tv_sec as u64) * 1000_000_000 + (ts.tv_nsec as u64)
13}
14
15/// System-wide realtime clock. It is generally synchronized with the clock of 
16/// the master server through the ntp protocol.
17pub fn current_realtime() -> u64 {
18    let mut ts = libc::timespec {
19        tv_sec: 0,
20        tv_nsec: 0,
21    };
22    unsafe { libc::clock_gettime(libc::CLOCK_REALTIME, &mut ts) };
23
24    (ts.tv_sec as u64) * 1000_000_000 + (ts.tv_nsec as u64)
25}
26
27pub fn delta_of_mono_real_time() -> u64 {
28    let x1 = current_monotime();
29    let y1 = current_realtime();
30    let y2 = current_realtime();
31    let x2 = current_monotime();
32    (y2 - x2 + y1 - x1) / 2
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38    #[test]
39    fn test_timestamp_current_monotime() {
40        assert_ne!(current_monotime(), 0);
41    }
42
43    #[test]
44    fn test_timestamp_current_realtime() {
45        assert_ne!(current_realtime(), 0);
46    }
47
48    #[test]
49    fn test_timestamp_delta_of_mono_real_time() {
50        assert_ne!(delta_of_mono_real_time(), 0);
51    }
52}