SystemMonitor: Fix CPU usage calculation

Casting u64 to float is probably not a safe thing to do. Also, keep
time deltas in u64 values as they can easily wrap between calculations.
This fixes CPU usage calculation when a process is spinning in a loop.
This commit is contained in:
Tom 2021-09-04 13:24:03 -06:00 committed by Andreas Kling
parent dcc9db48c5
commit d14d68c462
Notes: sideshowbarker 2024-07-18 04:45:29 +09:00

View file

@ -391,11 +391,11 @@ void ProcessModel::update()
continue;
}
auto& thread = *it.value;
u32 time_scheduled_diff = (thread.current_state.time_user + thread.current_state.time_kernel)
u64 time_scheduled_diff = (thread.current_state.time_user + thread.current_state.time_kernel)
- (thread.previous_state.time_user + thread.previous_state.time_kernel);
u32 time_scheduled_diff_kernel = thread.current_state.time_kernel - thread.previous_state.time_kernel;
thread.current_state.cpu_percent = total_time_scheduled_diff > 0 ? ((float)time_scheduled_diff * 100) / (float)total_time_scheduled_diff : 0;
thread.current_state.cpu_percent_kernel = total_time_scheduled_diff > 0 ? ((float)time_scheduled_diff_kernel * 100) / (float)total_time_scheduled_diff : 0;
u64 time_scheduled_diff_kernel = thread.current_state.time_kernel - thread.previous_state.time_kernel;
thread.current_state.cpu_percent = total_time_scheduled_diff > 0 ? (float)((time_scheduled_diff * 1000) / total_time_scheduled_diff) / 10.0f : 0;
thread.current_state.cpu_percent_kernel = total_time_scheduled_diff > 0 ? (float)((time_scheduled_diff_kernel * 1000) / total_time_scheduled_diff) / 10.0f : 0;
if (it.value->current_state.pid != 0) {
auto& cpu_info = m_cpus[thread.current_state.cpu];
cpu_info.total_cpu_percent += thread.current_state.cpu_percent;