cpu_monitor/
lib.rs

1
2#[cfg(windows)]
3extern crate winapi;
4#[cfg(unix)]
5extern crate linux_proc;
6
7use std::time;
8use std::ops;
9use std::io;
10
11mod imp;
12
13/// Like `std::time::Instant`, but with information about the cpu usage stats.
14#[derive(Debug, Copy, Clone)]
15pub struct CpuInstant {
16    instant: time::Instant,
17    cpu_total: f64,
18    cpu_idle: f64,
19}
20
21impl CpuInstant {
22    /// Get the current instant.
23    ///
24    /// The main constructor method of the crate.
25    pub fn now() -> io::Result<CpuInstant> {
26        let (cpu_total, cpu_idle) = imp::get_cpu_totals()?;
27        Ok(CpuInstant {
28            instant: time::Instant::now(),
29            cpu_total,
30            cpu_idle,
31        })
32    }
33
34    /// Get the wrapped `time::Instant`.
35    pub fn instant(&self) -> time::Instant {
36        self.instant
37    }
38}
39
40impl ops::Sub for CpuInstant {
41    type Output = CpuDuration;
42
43    fn sub(self, rhs: Self) -> Self::Output {
44        CpuDuration {
45            duration: self.instant - rhs.instant,
46            cpu_total: self.cpu_total - rhs.cpu_total,
47            cpu_idle: self.cpu_idle - rhs.cpu_idle,
48        }
49    }
50}
51
52/// Like `std::time::Duration`, but with information about the cpu usage stats.
53///
54/// The way to get this is to subtract one `CpuInstant` from another.
55#[derive(Debug, Copy, Clone)]
56pub struct CpuDuration {
57    duration: time::Duration,
58    cpu_total: f64,
59    cpu_idle: f64,
60}
61
62impl CpuDuration {
63    /// The gap between samples.
64    pub fn duration(&self) -> time::Duration {
65        self.duration
66    }
67
68    /// The proportion of the time spent idle (between 0 and 1).
69    pub fn idle(&self) -> f64 {
70        self.cpu_idle / self.cpu_total
71    }
72
73    /// The proportion of the time spent not idle (between 0 and 1).
74    pub fn non_idle(&self) -> f64 {
75        1.0 - self.idle()
76    }
77}
78