Skip to main content

phc_watch/
phc_watch.rs

1//! Reads a PTP hardware clock beside the monotonic clock for a while and
2//! prints any reading that strays from the others.
3//!
4//!     cargo run -p raw-ether --example phc_watch -- <index> <seconds>
5
6use std::time::{Duration, Instant};
7
8use raw_ether::clock::{HardwareClock, monotonic_now};
9
10fn main() -> std::io::Result<()> {
11    let mut args = std::env::args().skip(1);
12    let index = args.next().and_then(|text| text.parse().ok()).unwrap_or(0);
13    let seconds = args.next().and_then(|text| text.parse().ok()).unwrap_or(60);
14    let clock = HardwareClock::open(index)?;
15    let until = Instant::now() + Duration::from_secs(seconds);
16    let mut last: Option<i128> = None;
17    let mut reads = 0u64;
18    let mut strays = 0u64;
19    while Instant::now() < until {
20        let before = monotonic_now().as_nanos() as i128;
21        let phc = clock.now()?.as_nanos() as i128;
22        let after = monotonic_now().as_nanos() as i128;
23        let offset = phc - (before + after) / 2;
24        reads += 1;
25        if let Some(previous) = last
26            && (offset - previous).abs() > 100_000
27        {
28            strays += 1;
29            println!(
30                "read {reads}: offset moved {} ns (read took {} ns)",
31                offset - previous,
32                after - before
33            );
34        }
35        last = Some(offset);
36        std::thread::sleep(Duration::from_micros(500));
37    }
38    println!("{reads} reads, {strays} strays");
39    Ok(())
40}