pub struct Sampler { /* private fields */ }Expand description
Measures CPU usage between samples. Owned by the caller: two samplers never
disturb each other (there is no hidden global baseline). sample never
blocks and allocates nothing; sample_per_core_into allocates nothing
unless CPUs were hot-plugged since the previous sample.
use std::time::Duration;
use sys_lib as sys;
let mut cpu = sys::cpu::Sampler::new()?;
let mut per_core = vec![sys::Percent::ZERO; sys::cpu::logical()];
loop {
std::thread::sleep(Duration::from_secs(5));
let u = cpu.sample_per_core_into(&mut per_core)?;
println!("used {} (user {}, system {}, steal {:?})", u.used(), u.user, u.system, u.steal);
}Implementations§
Source§impl Sampler
impl Sampler
Sourcepub fn sample(&mut self) -> Result<Usage>
pub fn sample(&mut self) -> Result<Usage>
Usage since the previous sample.
§Errors
TooSoon when no tick passed on the OS’s counters since the previous
sample (about 10 ms on Linux: E-21), or when they went backwards, which
re-bases the sampler (E-20). Never a meaningless 0% or 100%.
Sourcepub fn sample_per_core(&mut self) -> Result<(Usage, Vec<Percent>)>
pub fn sample_per_core(&mut self) -> Result<(Usage, Vec<Percent>)>
Usage since the previous sample, total and per core (allocates the
Vec).
§Errors
Sourcepub fn sample_per_core_into(&mut self, out: &mut [Percent]) -> Result<Usage>
pub fn sample_per_core_into(&mut self, out: &mut [Percent]) -> Result<Usage>
Usage since the previous sample, writing each core’s busy share into
out (Tier 3: no allocation). Entries past the number of cores are left
as they were. A core whose counters went backwards, or did not move,
reads 0% for this interval and is re-based (E-20); the total is
unaffected.
§Errors
TooLarge without writing anything when out is shorter than the
number of cores (on Linux, the highest CPU number plus one: an offline
CPU keeps its slot and reads 0%); TooSoon as
sample; Unsupported per core on Windows with
more than 64 logical processors or more than one processor group.