1use core::time::Duration;
5use std::time::Instant;
6
7use crate::{Error, Percent, Result};
8
9pub 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
18#[non_exhaustive]
19pub struct Times {
20 pub user: Duration,
22 pub nice: Duration,
24 pub system: Duration,
26 pub idle: Duration,
28 pub iowait: Duration,
30 pub irq: Duration,
32 pub softirq: Duration,
34 pub steal: Duration,
36}
37
38impl Times {
39 fn total(&self) -> Duration {
40 self.busy() + self.idle + self.iowait
41 }
42
43 fn busy(&self) -> Duration {
45 self.user + self.nice + self.system + self.irq + self.softirq + self.steal
46 }
47
48 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#[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#[derive(Clone, Copy, Debug)]
78#[non_exhaustive]
79pub struct Usage {
80 pub user: Percent,
82 pub system: Percent,
84 pub idle: Percent,
86 pub iowait: Option<Percent>,
88 pub steal: Option<Percent>,
90 pub irq: Option<Percent>,
92 pub interval: Duration,
94}
95
96impl Usage {
97 #[must_use]
99 pub fn used(&self) -> Percent {
100 self.free().complement()
101 }
102
103 #[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 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
130pub fn times() -> Result<Times> {
138 crate::sys::cpu_times()
139}
140
141pub fn usage() -> Result<Usage> {
154 usage_over(DEFAULT_WINDOW)
155}
156
157pub 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
169pub fn used() -> Result<Percent> {
181 usage().map(|u| u.used())
182}
183
184pub fn free() -> Result<Percent> {
191 usage().map(|u| u.free())
192}
193
194#[derive(Debug)]
213pub struct Sampler {
214 total: Times,
216 at: Instant,
217 cores_total: Times,
222 cores: Vec<Times>,
223 scratch: Vec<Times>,
224 cores_at: Instant,
225}
226
227impl Sampler {
228 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 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 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 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 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 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 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
340fn 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
350fn 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 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 ×(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 assert!(Usage::from_delta(&Times::default(), ALL, ms(5)).is_none());
422 assert!(times(5, 0, 0, 0, 0).since(×(6, 0, 0, 0, 0)).is_none());
423 let d = times(7, 1, 2, 0, 0).since(×(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}