Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve CPU usage efficiency #1448

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open

Conversation

provrb
Copy link

@provrb provrb commented Jan 4, 2025

Problem

The compute_cpu_usage function relied on redundant operations and inefficient handling of cached system times. This could lead to unnecessary updates to system times, resulting in reduced efficiency and increased overhead.

Solution

I updated the function to use cached values unless the time elapsed since the previous values were cached exceeds MINIMUM_CPU_UPDATE_INTERVAL, ensuring system times are only refreshed when necessary.

  • Specifically minimizes the amount of calls to GetSystemTimes, and filetime_to_u64.

Now, after each call to compute_cpu_usage if the last time these values were retrieved ( a call to GetSystemTimes took place ) is less than MINIMUM_CPU_UPDATE_INTERVAL ( system values haven't updated ) the function will use the values used previously. Otherwise, GetSystemTimes will be called, values will be retrieved, and an Instant::now() value will be saved in cpu_calc_values to determine the time GetSystemTimes was last called.

Tests

  • All 237 existing tests passed and ran with cargo test.

Other

  • Both cargo fmt and cargo clippy were ran successfully.

let global_kernel_time = filetime_to_u64(fglobal_kernel_time);
let global_user_time = filetime_to_u64(fglobal_user_time);
// by default, use previous values
let mut global_kernel_time: u64 = p.cpu_calc_values.old_system_sys_cpu;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At this point, why not just return the previously computed cpu usage?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I apologize for my significant oversight. I revised the code to return the unchanged process CPU usage if the last_update field hasn't exceeded the time it takes to update the CPU values. It should be good now. Again, passed all cargo fmt, clippy and test commands.

…rather than re-calculating using old values.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants