Skip to main content

sys_lib/cpu/
usage.rs

1//! CPU usage: the share of non-idle time between two readings of the OS's
2//! cumulative counters.
3
4use core::time::Duration;
5use std::time::Instant;
6
7use crate::{Error, Percent, Result};
8
9/// The interval [`usage`] measures over: 100 ms.
10pub const DEFAULT_WINDOW: Duration = Duration::from_millis(100);
11
12const MIN_WINDOW: Duration = Duration::from_millis(10);
13const MAX_WINDOW: Duration = Duration::from_secs(10);
14
15/// The OS's cumulative CPU time counters, since boot (Tier 3). States an OS
16/// does not keep are zero.
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
18#[non_exhaustive]
19pub struct Times {
20    /// Running user code.
21    pub user: Duration,
22    /// Running user code at a lowered priority (Unix).
23    pub nice: Duration,
24    /// Running kernel code (Windows: kernel time minus idle).
25    pub system: Duration,
26    /// Doing nothing.
27    pub idle: Duration,
28    /// Idle while I/O was outstanding (Linux).
29    pub iowait: Duration,
30    /// Serving hardware interrupts (Linux).
31    pub irq: Duration,
32    /// Serving software interrupts (Linux).
33    pub softirq: Duration,
34    /// Taken by the hypervisor for other guests (Linux virtual machines).
35    pub steal: Duration,
36}
37
38impl Times {
39    fn total(&self) -> Duration {
40        self.busy() + self.idle + self.iowait
41    }
42
43    /// Busy time: steal counts as busy (the CPU was not ours to use).
44    fn busy(&self) -> Duration {
45        self.user + self.nice + self.system + self.irq + self.softirq + self.steal
46    }
47
48    /// `self - earlier`, field by field, or `None` when any counter went
49    /// backwards (a CPU offlined and back, a VM migration, a wrap: E-20).
50    fn since(&self, earlier: &Times) -> Option<Times> {
51        Some(Times {
52            user: self.user.checked_sub(earlier.user)?,
53            nice: self.nice.checked_sub(earlier.nice)?,
54            system: self.system.checked_sub(earlier.system)?,
55            idle: self.idle.checked_sub(earlier.idle)?,
56            iowait: self.iowait.checked_sub(earlier.iowait)?,
57            irq: self.irq.checked_sub(earlier.irq)?,
58            softirq: self.softirq.checked_sub(earlier.softirq)?,
59            steal: self.steal.checked_sub(earlier.steal)?,
60        })
61    }
62}
63
64/// Which states a platform's counters distinguish.
65#[derive(Clone, Copy, Debug)]
66pub(crate) struct States {
67    pub(crate) iowait: bool,
68    pub(crate) steal: bool,
69    pub(crate) irq: bool,
70}
71
72/// CPU usage over an interval.
73///
74/// Steal counts as busy (the CPU was not available to us) and iowait as idle
75/// (the CPU was free to run other work); both are also reported on their own
76/// where the OS keeps them (E-24, E-25).
77#[derive(Clone, Copy, Debug)]
78#[non_exhaustive]
79pub struct Usage {
80    /// Running user code (nice included).
81    pub user: Percent,
82    /// Running kernel code.
83    pub system: Percent,
84    /// Doing nothing, iowait excluded.
85    pub idle: Percent,
86    /// Idle while I/O was outstanding (Linux).
87    pub iowait: Option<Percent>,
88    /// Taken by the hypervisor for other guests (Linux virtual machines).
89    pub steal: Option<Percent>,
90    /// Serving interrupts (Linux: hardware and software).
91    pub irq: Option<Percent>,
92    /// The time the values cover.
93    pub interval: Duration,
94}
95
96impl Usage {
97    /// The busy share: everything but idle and iowait.
98    #[must_use]
99    pub fn used(&self) -> Percent {
100        self.free().complement()
101    }
102
103    /// The idle share, iowait included.
104    #[must_use]
105    pub fn free(&self) -> Percent {
106        let iowait = self.iowait.map_or(0.0, Percent::value);
107        Percent::from_value(self.idle.value() + iowait)
108    }
109
110    /// The usage a counter difference amounts to, or `None` when no time
111    /// passed on the OS's counters.
112    fn from_delta(d: &Times, states: States, interval: Duration) -> Option<Usage> {
113        let total = d.total().as_nanos();
114        if total == 0 {
115            return None;
116        }
117        let share = |part: Duration| Percent::from_ratio_u128(part.as_nanos(), total);
118        Some(Usage {
119            user: share(d.user + d.nice),
120            system: share(d.system),
121            idle: share(d.idle),
122            iowait: states.iowait.then(|| share(d.iowait)),
123            steal: states.steal.then(|| share(d.steal)),
124            irq: states.irq.then(|| share(d.irq + d.softirq)),
125            interval,
126        })
127    }
128}
129
130/// The OS's cumulative CPU time counters (Tier 3). One reading only gives the
131/// average since boot; [`Sampler`] gives usage.
132///
133/// # Errors
134///
135/// `NotFound` or `PermissionDenied` when a sandbox hides the counters;
136/// `Malformed` when they do not parse.
137pub fn times() -> Result<Times> {
138    crate::sys::cpu_times()
139}
140
141/// CPU usage over the next 100 ms. **Blocks for [`DEFAULT_WINDOW`]**; a
142/// monitor keeps a [`Sampler`] instead.
143///
144/// ```
145/// let u = sys_lib::cpu::usage()?;
146/// println!("CPU {} (user {}, system {})", u.used(), u.user, u.system);
147/// # Ok::<(), sys_lib::Error>(())
148/// ```
149///
150/// # Errors
151///
152/// As [`Sampler::sample`].
153pub fn usage() -> Result<Usage> {
154    usage_over(DEFAULT_WINDOW)
155}
156
157/// CPU usage over `window`, clamped to 10 ms ..= 10 s. **Blocks for the
158/// window.**
159///
160/// # Errors
161///
162/// As [`Sampler::sample`].
163pub fn usage_over(window: Duration) -> Result<Usage> {
164    let mut sampler = Sampler::total_only()?;
165    std::thread::sleep(window.clamp(MIN_WINDOW, MAX_WINDOW));
166    sampler.sample()
167}
168
169/// The busy share over the next 100 ms: `usage()?.used()`. **Blocks for
170/// [`DEFAULT_WINDOW`].**
171///
172/// ```
173/// println!("CPU {}", sys_lib::cpu::used()?);   // "12.4%"
174/// # Ok::<(), sys_lib::Error>(())
175/// ```
176///
177/// # Errors
178///
179/// As [`Sampler::sample`].
180pub fn used() -> Result<Percent> {
181    usage().map(|u| u.used())
182}
183
184/// The idle share over the next 100 ms: `usage()?.free()`. **Blocks for
185/// [`DEFAULT_WINDOW`].**
186///
187/// # Errors
188///
189/// As [`Sampler::sample`].
190pub fn free() -> Result<Percent> {
191    usage().map(|u| u.free())
192}
193
194/// Measures CPU usage between samples. Owned by the caller: two samplers never
195/// disturb each other (there is no hidden global baseline). `sample` never
196/// blocks and allocates nothing; `sample_per_core_into` allocates nothing
197/// unless CPUs were hot-plugged since the previous sample.
198///
199/// ```no_run
200/// use std::time::Duration;
201/// use sys_lib as sys;
202///
203/// let mut cpu = sys::cpu::Sampler::new()?;
204/// let mut per_core = vec![sys::Percent::ZERO; sys::cpu::logical()];
205/// loop {
206///     std::thread::sleep(Duration::from_secs(5));
207///     let u = cpu.sample_per_core_into(&mut per_core)?;
208///     println!("used {} (user {}, system {}, steal {:?})", u.used(), u.user, u.system, u.steal);
209/// }
210/// # Ok::<(), sys_lib::Error>(())
211/// ```
212#[derive(Debug)]
213pub struct Sampler {
214    /// The baseline of `sample`, from `times()`.
215    total: Times,
216    at: Instant,
217    /// The baseline of `sample_per_core_into`: its own total (from the same
218    /// read as the cores, which on macOS is a wider sum than `times()`), the
219    /// cores, and a scratch buffer of the same length. Kept apart from the
220    /// total's, so mixing the two calls never compares unlike counters.
221    cores_total: Times,
222    cores: Vec<Times>,
223    scratch: Vec<Times>,
224    cores_at: Instant,
225}
226
227impl Sampler {
228    /// Takes the first reading, of the total and of every core.
229    ///
230    /// # Errors
231    ///
232    /// As [`times`].
233    pub fn new() -> Result<Sampler> {
234        let total = times()?;
235        let mut cores = vec![Times::default(); super::logical()];
236        let (cores_total, n) = match read_cores(&mut cores) {
237            Ok(r) => r,
238            // No per-core counters here (Windows past 64 processors): the
239            // total still works; the per-core calls say Unsupported.
240            Err(Error::Unsupported { .. }) => (total, 0),
241            Err(e) => return Err(e),
242        };
243        cores.truncate(n);
244        let now = Instant::now();
245        Ok(Sampler {
246            total,
247            at: now,
248            cores_total,
249            scratch: vec![Times::default(); cores.len()],
250            cores,
251            cores_at: now,
252        })
253    }
254
255    /// A sampler for the total only, for the blocking functions.
256    fn total_only() -> Result<Sampler> {
257        let now = Instant::now();
258        let total = times()?;
259        Ok(Sampler {
260            total,
261            at: now,
262            cores_total: total,
263            cores: Vec::new(),
264            scratch: Vec::new(),
265            cores_at: now,
266        })
267    }
268
269    /// Usage since the previous sample.
270    ///
271    /// # Errors
272    ///
273    /// `TooSoon` when no tick passed on the OS's counters since the previous
274    /// sample (about 10 ms on Linux: E-21), or when they went backwards, which
275    /// re-bases the sampler (E-20). Never a meaningless 0% or 100%.
276    pub fn sample(&mut self) -> Result<Usage> {
277        let now = times()?;
278        let at = Instant::now();
279        let usage = between(&now, &self.total, at.duration_since(self.at));
280        self.total = now;
281        self.at = at;
282        usage
283    }
284
285    /// Usage since the previous sample, total and per core (allocates the
286    /// `Vec`).
287    ///
288    /// # Errors
289    ///
290    /// As [`sample_per_core_into`](Sampler::sample_per_core_into).
291    pub fn sample_per_core(&mut self) -> Result<(Usage, Vec<Percent>)> {
292        let mut out = vec![Percent::ZERO; self.scratch.len().max(super::logical())];
293        let usage = self.sample_per_core_into(&mut out)?;
294        out.truncate(self.cores.len());
295        Ok((usage, out))
296    }
297
298    /// Usage since the previous sample, writing each core's busy share into
299    /// `out` (Tier 3: no allocation). Entries past the number of cores are left
300    /// as they were. A core whose counters went backwards, or did not move,
301    /// reads 0% for this interval and is re-based (E-20); the total is
302    /// unaffected.
303    ///
304    /// # Errors
305    ///
306    /// `TooLarge` without writing anything when `out` is shorter than the
307    /// number of cores (on Linux, the highest CPU number plus one: an offline
308    /// CPU keeps its slot and reads 0%); `TooSoon` as
309    /// [`sample`](Sampler::sample); `Unsupported` per core on Windows with
310    /// more than 64 logical processors or more than one processor group.
311    pub fn sample_per_core_into(&mut self, out: &mut [Percent]) -> Result<Usage> {
312        let (total, n) = read_cores(&mut self.scratch)?;
313        let at = Instant::now();
314        if out.len() < n {
315            return Err(Error::TooLarge {
316                what: "per-core CPU usage",
317                limit: out.len() as u64,
318            });
319        }
320        let interval = at.duration_since(self.cores_at);
321        let usage = between(&total, &self.cores_total, interval);
322        for (i, now) in self.scratch[..n].iter().enumerate() {
323            out[i] = self
324                .cores
325                .get(i)
326                .and_then(|old| now.since(old))
327                .and_then(|d| Usage::from_delta(&d, crate::sys::CPU_STATES, interval))
328                .map_or(Percent::ZERO, |u| u.used());
329        }
330        // The new readings become the baseline; both buffers keep their size,
331        // so nothing is allocated in the steady state.
332        self.cores.resize(n, Times::default());
333        self.cores.copy_from_slice(&self.scratch[..n]);
334        self.cores_at = at;
335        self.cores_total = total;
336        usage
337    }
338}
339
340/// The usage between two readings `interval` apart.
341fn between(now: &Times, then: &Times, interval: Duration) -> Result<Usage> {
342    let too_soon = || Error::TooSoon {
343        elapsed: interval,
344        minimum: crate::sys::CPU_TICK,
345    };
346    let delta = now.since(then).ok_or_else(too_soon)?;
347    Usage::from_delta(&delta, crate::sys::CPU_STATES, interval).ok_or_else(too_soon)
348}
349
350/// The total and per-core counters, into `buf`. When more cores report than
351/// `buf` holds (hot-plug, E-22), it grows once and reads again: the only
352/// allocation in a sampler's steady state.
353fn read_cores(buf: &mut Vec<Times>) -> Result<(Times, usize)> {
354    let (total, n) = match crate::sys::cpu_times_per_core(buf) {
355        Err(Error::TooLarge { .. }) => {
356            buf.resize(buf.len() * 2 + super::logical(), Times::default());
357            crate::sys::cpu_times_per_core(buf)?
358        }
359        r => r?,
360    };
361    Ok((total, n.min(buf.len())))
362}
363
364#[cfg(test)]
365mod tests {
366    use super::*;
367
368    const ALL: States = States {
369        iowait: true,
370        steal: true,
371        irq: true,
372    };
373
374    fn ms(n: u64) -> Duration {
375        Duration::from_millis(n)
376    }
377
378    fn times(user: u64, system: u64, idle: u64, iowait: u64, steal: u64) -> Times {
379        Times {
380            user: ms(user),
381            system: ms(system),
382            idle: ms(idle),
383            iowait: ms(iowait),
384            steal: ms(steal),
385            ..Times::default()
386        }
387    }
388
389    #[test]
390    fn test_cpu_usage_steal_busy_iowait_idle() {
391        // E-24, E-25: 1000 ms: user 300, system 100, idle 400, iowait 100, steal 100.
392        let d = times(300, 100, 400, 100, 100);
393        let u = Usage::from_delta(&d, ALL, ms(1000)).unwrap();
394        assert_eq!(u.user.to_string(), "30.0%");
395        assert_eq!(u.idle.to_string(), "40.0%");
396        assert_eq!(u.iowait.unwrap().to_string(), "10.0%");
397        assert_eq!(u.steal.unwrap().to_string(), "10.0%");
398        assert_eq!(u.free().to_string(), "50.0%");
399        assert_eq!(u.used().to_string(), "50.0%");
400    }
401
402    #[test]
403    fn test_cpu_usage_states_a_platform_lacks_are_none() {
404        let u = Usage::from_delta(
405            &times(1, 1, 2, 0, 0),
406            States {
407                iowait: false,
408                steal: false,
409                irq: false,
410            },
411            ms(4),
412        )
413        .unwrap();
414        assert_eq!((u.iowait, u.steal, u.irq), (None, None, None));
415        assert_eq!(u.used().to_string(), "50.0%");
416    }
417
418    #[test]
419    fn test_cpu_usage_no_time_and_backwards_counters() {
420        // E-21: no tick passed. E-20: a counter went backwards.
421        assert!(Usage::from_delta(&Times::default(), ALL, ms(5)).is_none());
422        assert!(times(5, 0, 0, 0, 0).since(&times(6, 0, 0, 0, 0)).is_none());
423        let d = times(7, 1, 2, 0, 0).since(&times(5, 1, 1, 0, 0)).unwrap();
424        assert_eq!((d.user, d.idle), (ms(2), ms(1)));
425    }
426
427    #[test]
428    fn test_cpu_sampler_live_never_out_of_range() {
429        let mut s = Sampler::new().unwrap();
430        let mut out = vec![Percent::FULL; crate::cpu::logical() + 4];
431        std::thread::sleep(ms(30));
432        match s.sample_per_core_into(&mut out) {
433            Ok(u) => {
434                assert!(u.used() <= Percent::FULL && u.interval >= ms(25));
435                assert_eq!(
436                    out[crate::cpu::logical() + 3],
437                    Percent::FULL,
438                    "past the cores is untouched"
439                );
440            }
441            Err(Error::TooSoon { .. } | Error::Unsupported { .. }) => {}
442            Err(e) => panic!("{e}"),
443        }
444        let mut short = [Percent::ZERO; 0];
445        if crate::cpu::logical() > 0 {
446            assert!(matches!(
447                s.sample_per_core_into(&mut short),
448                Err(Error::TooLarge { .. }) | Err(Error::Unsupported { .. })
449            ));
450        }
451        std::thread::sleep(ms(30));
452        if let Ok(u) = s.sample() {
453            assert!(u.used() <= Percent::FULL);
454        }
455        let u = usage_over(ms(30)).unwrap();
456        assert!(u.used() <= Percent::FULL);
457    }
458}