To calculate CPU usage percentages over a period of time, use the CpuTimesPercentCollector. This collector tracks the delta between consecutive calls to provide non-blocking percentage values.
- Initialize the collector using
CpuTimesPercentCollector::new(). - Call
cpu_times_percent() to get the aggregate CPU usage. - Call
cpu_times_percent_percpu() to get usage for each individual CPU core.
Note: The first call to these methods will return the usage since the collector was initialized. Subsequent calls return the usage since the previous call. If the time elapsed between calls is too short, the returned values may be zero.
let mut cpu_times_percent_collector = psutil::cpu::CpuTimesPercentCollector::new().unwrap();
// Get aggregate CPU usage
let cpu_times_percent = cpu_times_percent_collector.cpu_times_percent().unwrap();
// Get per-CPU usage
let cpu_times_percent_percpu = cpu_times_percent_collector.cpu_times_percent_percpu().unwrap();