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
use std::io::Error;
use std::time::Duration;

#[cfg_attr(target_os = "linux", path = "pthread.rs")]
#[cfg_attr(any(target_os = "macos", target_os = "ios"), path = "mach/mod.rs")]
mod os;

pub use os::cpu_clock_for_current_thread;

#[cfg(target_family = "unix")]
mod unix;

pub trait Clock: Sized + Send {
    fn get_time(&self) -> Result<Duration, Error>;
}

#[cfg(test)]
mod tests {
    use super::{cpu_clock_for_current_thread, Clock};

    #[test]
    fn valid_measurement() {
        let clock = cpu_clock_for_current_thread().unwrap();

        let mut samples = std::iter::repeat::<()>(())
            .map(|_| clock.get_time().unwrap())
            .step_by(50000);

        let mut last_time = samples.next().unwrap();

        let samples = samples
            .take(5)
            .map(|this_time| {
                assert!(this_time > last_time);
                let diff = (this_time - last_time).as_secs_f64();
                last_time = this_time;
                diff
            })
            .collect::<Vec<f64>>();

        let avg = samples.iter().sum::<f64>() / (samples.len() as f64);

        let mean_abs_dev_scaled = samples
            .iter()
            .map(|sample| (sample - avg).abs())
            .sum::<f64>()
            / (samples.len() as f64)
            / avg;

        println!(
            "
durations of timing 50000 samples
==================================
{:#?}
----------------------------------
avg: {}, mad scaled: {}",
            samples, avg, mean_abs_dev_scaled
        );

        assert!(mean_abs_dev_scaled < 0.1); // test that samples are on average within 10% of the mean
    }
}