Skip to content

Commit

Permalink
Improve Windows CPU usage efficiency (#1448)
Browse files Browse the repository at this point in the history
  • Loading branch information
provrb authored Jan 10, 2025
1 parent c491e0a commit be49f99
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions src/windows/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use std::process::{self, ExitStatus};
use std::ptr::null_mut;
use std::str;
use std::sync::{Arc, OnceLock};
use std::time::Instant;

use libc::c_void;
use ntapi::ntexapi::SYSTEM_PROCESS_INFORMATION;
Expand Down Expand Up @@ -47,6 +48,8 @@ use windows::Win32::System::Threading::{
};
use windows::Win32::UI::Shell::CommandLineToArgvW;

use super::MINIMUM_CPU_UPDATE_INTERVAL;

impl fmt::Display for ProcessStatus {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(match *self {
Expand Down Expand Up @@ -196,6 +199,7 @@ struct CPUsageCalculationValues {
old_process_user_cpu: u64,
old_system_sys_cpu: u64,
old_system_user_cpu: u64,
last_update: Instant,
}

impl CPUsageCalculationValues {
Expand All @@ -205,6 +209,7 @@ impl CPUsageCalculationValues {
old_process_user_cpu: 0,
old_system_sys_cpu: 0,
old_system_user_cpu: 0,
last_update: Instant::now(),
}
}
}
Expand Down Expand Up @@ -951,6 +956,11 @@ fn check_sub(a: u64, b: u64) -> u64 {
/// Before changing this function, you must consider the following:
/// <https://github.com/GuillaumeGomez/sysinfo/issues/459>
pub(crate) fn compute_cpu_usage(p: &mut ProcessInner, nb_cpus: u64) {
if p.cpu_calc_values.last_update.elapsed() <= MINIMUM_CPU_UPDATE_INTERVAL {
// cpu usage hasn't updated. p.cpu_usage remains the same
return;
}

unsafe {
let mut ftime: FILETIME = zeroed();
let mut fsys: FILETIME = zeroed();
Expand All @@ -962,14 +972,17 @@ pub(crate) fn compute_cpu_usage(p: &mut ProcessInner, nb_cpus: u64) {
if let Some(handle) = p.get_handle() {
let _err = GetProcessTimes(handle, &mut ftime, &mut ftime, &mut fsys, &mut fuser);
}
// FIXME: should these values be stored in one place to make use of
// `MINIMUM_CPU_UPDATE_INTERVAL`?

// system times have changed, we need to get most recent system times
// and update the cpu times cache, as well as global_kernel_time and global_user_time
let _err = GetSystemTimes(
Some(&mut fglobal_idle_time),
Some(&mut fglobal_kernel_time),
Some(&mut fglobal_user_time),
);

p.cpu_calc_values.last_update = Instant::now();

let sys = filetime_to_u64(fsys);
let user = filetime_to_u64(fuser);
let global_kernel_time = filetime_to_u64(fglobal_kernel_time);
Expand Down

0 comments on commit be49f99

Please sign in to comment.