Skip to content

Commit

Permalink
Fix Windows usage and improve test
Browse files Browse the repository at this point in the history
  • Loading branch information
bruceg committed Sep 21, 2023
1 parent 61bdf99 commit 8e14b45
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,7 @@ mod test {
if System::IS_SUPPORTED {
let mut s = System::new();

// Grab the intial accumulated CPU usages
s.refresh_cpu();
s.refresh_processes();
s.refresh_processes(); // Needed on some OS to fully populate the accumulated CPU usage
Expand All @@ -272,17 +273,22 @@ mod test {
.iter()
.map(|(pid, proc)| (*pid, proc.total_accumulated_cpu_usage()))
.collect();

// All accumulated CPU usages will be non-negative.
all_procs.values().for_each(|&usage| assert!(usage >= 0.0));
// At least one will be positive.
assert!(all_procs.values().any(|&usage| usage > 0.0));

// Wait a bit to update CPU usage values
std::thread::sleep(System::MINIMUM_CPU_UPDATE_INTERVAL);
s.refresh_processes();
let duration = Instant::now().duration_since(first_time).as_secs_f32();

// They will still all be non-negative.
s.processes()
.values()
.for_each(|proc| assert!(proc.total_accumulated_cpu_usage() >= 0.0));

// They will all have either remained the same or
// increased no more than a valid amount.
let max_delta = s.cpus().len() as f32 * duration;
Expand All @@ -298,6 +304,14 @@ mod test {
);
}
});

// At least one of them will have accumulated some CPU time.
#[cfg(not(windows))] // Windows CPU timers appear to have insufficient resolution
assert!(s.processes().iter().any(|(pid, proc)| {
all_procs
.get(pid)
.map_or(false, |&prev| proc.total_accumulated_cpu_usage() > prev)
}));
}
}

Expand Down
4 changes: 4 additions & 0 deletions src/windows/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ use winapi::um::winnt::{
RTL_OSVERSIONINFOEXW, TOKEN_QUERY, TOKEN_USER, ULARGE_INTEGER,
};

const FILETIMES_PER_SECOND: f32 = 10_000_000.0; // 100 nanosecond units

impl fmt::Display for ProcessStatus {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(match *self {
Expand Down Expand Up @@ -207,6 +209,7 @@ pub struct Process {
written_bytes: u64,
}

#[derive(Debug)]
struct CPUsageCalculationValues {
old_process_sys_cpu: u64,
old_process_user_cpu: u64,
Expand All @@ -229,6 +232,7 @@ impl CPUsageCalculationValues {
fn total_accumulated_cpu_usage(&self) -> f32 {
self.old_process_user_cpu
.saturating_add(self.old_process_sys_cpu) as f32
/ FILETIMES_PER_SECOND
}
}

Expand Down

0 comments on commit 8e14b45

Please sign in to comment.