我正在使用Win32 x64环境
也请转到下面的链接
我从此链接Collecting CPU Usage of a Process找到了答案
在 Windows 条件的第一个答案下,您可以看到如下代码片段:
double getCurrentValue(){
FILETIME ftime, fsys, fuser;
ULARGE_INTEGER now, sys, user;
double percent;
GetSystemTimeAsFileTime(&ftime);
memcpy(&now, &ftime, sizeof(FILETIME));
GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);
memcpy(&sys, &fsys, sizeof(FILETIME));
memcpy(&user, &fuser, sizeof(FILETIME));
percent = (sys.QuadPart - lastSysCPU.QuadPart) +
(user.QuadPart - lastUserCPU.QuadPart);
percent /= (now.QuadPart - lastCPU.QuadPart);
percent /= numProcessors;
lastCPU = now;
lastUserCPU = user;
lastSysCPU = sys;
return percent * 100;
}
//--------------------------- FOCUS -----------------------------//
percent = (sys.QuadPart - lastSysCPU.QuadPart) +(user.QuadPart - lastUserCPU.QuadPart); // ---(1)
percent /= (now.QuadPart - lastCPU.QuadPart); // ---(2)
percent /= numProcessors; // --- (3)
如(1)所示,将ULONGLONG(unsigned long long)赋值给double来给编译器
warning C4244: conversion from 'ULONGLONG' to 'double', possible loss of data
double precent
数据的值? (由于Ulonglong将64位整数数据转换为64位浮点数据)
precent
值会获得大于 100.00 的值作为时间戳,作为CPU使用率最佳答案
假设您在短时间内调用getCurrentValue
函数,则可以安全地将值强制转换为两倍。您还可以检查极端情况,以年为单位分隔 call 。
ULONGLONG used = (sys.QuadPart - lastSysCPU.QuadPart) + (user.QuadPart - lastUserCPU.QuadPart);
ULONGLONG elapsed = (now.QuadPart - lastCPU.QuadPart);
if ( elapsed == 0 )
{
// Now it is imposible, but it could be problem in future :)
// Do something sane here. For example restart calculation.
}
else
{
double percent = ( (double)used / (double)elapsed ) / numProcessors * 100.0;
// Clamp value for rounding errors in our or system code.
if ( percent > 100.0 )
percent = 100.0;
if ( elapsed >= ( 1ull << 53 ) || used >= ( 1ull << 53 ) )
{
// Set some flag that result could be not precise.
// For 'elapsed' this needs 28 years.
// 'used' could kick earlier: 28/num_processors years.
// But if you realy need only 4 or 5 digits you can
// ignore this case.
}
}