我正在努力将cpu使用情况监视器添加到进程监视器中,因此我选择使用NtQuerySystemInformation,因为它是我可以用来进行更准确计算的最低API 当cpu的使用率较高时,以下代码可以很好地工作,但是当cpu几乎处于空闲状态(10:30)时,它不会像任务管理器中那样显示使用率百分比 它不会显示低于26%的使用率,但任务管理器会显示15%或接近百分比的值
这是我的代码:
double accurate_usage() {
SYSTEM_INFO info = { 0 };
GetSystemInfo(&info);
DWORD proc_num = info.dwNumberOfProcessors;
PSYSTEM_PROCESSOR_PERFORMANCE_INFORMATION old_values = new SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION[proc_num];
PSYSTEM_PROCESSOR_PERFORMANCE_INFORMATION new_values = new SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION[proc_num];
FILETIME old_time = { 0 }, new_time = { 0 };
ULARGE_INTEGER uold_time = { 0 }, unew_time = { 0 };
ULONG size;
fNtQuerySystemInformation(SystemProcessorPerformanceInformation, old_values, sizeof(old_values[0]) * proc_num, &size);
GetSystemTimeAsFileTime(&old_time);
memcpy(&uold_time, &old_time, sizeof(FILETIME));
Sleep(1000);
fNtQuerySystemInformation(SystemProcessorPerformanceInformation, new_values, sizeof(old_values[0]) * proc_num, &size);
GetSystemTimeAsFileTime(&new_time);
memcpy(&unew_time, &new_time, sizeof(FILETIME));
double percent = 0.0;
for (DWORD i = 0; i < proc_num; ++i) {
double current_percent = (new_values[i].KernelTime.QuadPart - old_values[i].KernelTime.QuadPart) +
(new_values[i].UserTime.QuadPart - old_values[i].UserTime.QuadPart) -
(new_values[i].IdleTime.QuadPart - old_values[i].IdleTime.QuadPart);
current_percent /= (unew_time.QuadPart - uold_time.QuadPart);
current_percent /= proc_num;
current_percent *= 100;
percent += current_percent;
}
return percent;
}
答案 0 :(得分:0)
工作代码:
double accurate_usage() {
SYSTEM_INFO info = { 0 };
GetSystemInfo(&info);
DWORD proc_num = info.dwNumberOfProcessors;
PSYSTEM_PROCESSOR_PERFORMANCE_INFORMATION old_values = new SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION[proc_num];
PSYSTEM_PROCESSOR_PERFORMANCE_INFORMATION new_values = new SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION[proc_num];
FILETIME old_time = { 0 }, new_time = { 0 };
ULARGE_INTEGER uold_time = { 0 }, unew_time = { 0 };
ULONG size;
fNtQuerySystemInformation(SystemProcessorPerformanceInformation, old_values, sizeof(old_values[0]) * proc_num, &size);
GetSystemTimeAsFileTime(&old_time);
memcpy(&uold_time, &old_time, sizeof(FILETIME));
Sleep(1000);
fNtQuerySystemInformation(SystemProcessorPerformanceInformation, new_values, sizeof(old_values[0]) * proc_num, &size);
GetSystemTimeAsFileTime(&new_time);
memcpy(&unew_time, &new_time, sizeof(FILETIME));
double percent = 0.0;
for (DWORD i = 0; i < proc_num; ++i) {
double current_percent = (new_values[i].IdleTime.QuadPart - old_values[i].IdleTime.QuadPart) * 100 ;
current_percent /= ((new_values[i].KernelTime.QuadPart + new_values[i].UserTime.QuadPart) - (old_values[i].KernelTime.QuadPart + old_values[i].UserTime.QuadPart));
current_percent = 100 - current_percent;
percent += current_percent;
}
return percent / 10;
}