valpackett / systemstat

Rust library for getting system information | also on https://codeberg.org/valpackett/systemstat
https://crates.io/crates/systemstat
The Unlicense
616 stars 71 forks source link

CPU load output isn't showing actual load #84

Closed reza-ebrahimi closed 3 years ago

reza-ebrahimi commented 3 years ago

My 4 CPU cores are in 100% load but the cpu_load_aggregate output rarely goes to 10% of usage. Most of the times all of them are 0.

Following code is called every 250ms:

let sys = System::new();
match sys.cpu_load_aggregate() {
  Ok(cpu) => {
    let cpu = cpu.done().unwrap();
    Some(
      SystemStat {
        user: cpu.user * 100.0,
        nice: cpu.nice * 100.0,
        system: cpu.system * 100.0,
        interrupt: cpu.interrupt * 100.0,
        idle: cpu.idle * 100.0,
      }
      .into(),
    )
  }
  Err(x) => {
    println!("\nCPU load: error: {}", x);
    None
  }
}
valpackett commented 3 years ago

You are not using the measurement correctly — when cpu_load_aggregate() returns, you call done() immediately, which completely misses the point of why this is split into two steps :) You're measuring a tiny microsecond interval, not the interval you want to measure. The thread::sleep(Duration::from_secs(1)); in the example is there for a reason.

With a loop, what you probably want to do is store the cpu_load_aggregate() result for the next iteration and look at the current one. Something along the lines of:

/* every 250 ms */ {
    if let Ok(cpu) = load {
        let cpu = cpu.done().unwrap(); /* … */
    }
    load = sys.cpu_load_aggregate();
}
reza-ebrahimi commented 3 years ago

@unrelentingtech Thank you, It works now :)