找回密码
 立即注册
  • QQ空间
  • 回复
  • 收藏

GetSystemTimes来获取CPU的使用率和task manager结...

我用windows的API GetSystemTimes来获取CPU的使用率,但是得到的结果和task manager的结果差距很大,请问有大佬知道怎么获得和task manager CPU使用率差不多的值的方式么?下面是计算方式
__int64 CompareFileTime(FILETIME time1, FILETIME time2)
{
        //__int64 a = time1.dwHighDateTime << 32 | time1.dwLowDateTime;
        //__int64 b = time2.dwHighDateTime << 32 | time2.dwLowDateTime;
        //std::cout << "time 1 is "<<&time1 << "time 2 is " << &time2 << std::endl;
        //return (b - a);
        UINT64 i641 = (UINT64)time1.dwHighDateTime*(0xFFFFFFFFui64 + 1ui64) + (UINT64)time1.dwLowDateTime;
        UINT64 i642 = (UINT64)time2.dwHighDateTime*(0xFFFFFFFFui64 + 1ui64) + (UINT64)time2.dwLowDateTime;
        return i642 - i641;
}
void getSystemTimesExample() {
        GetSystemTimes(&lastIdleTime, &lastKernelTime, &lastUserTime);
        while (true) {
                Sleep(1000);
                GetSystemTimes(&currentIdleTime, &currentKernelTime, &currentUserTime);
                int idle = CompareFileTime(lastIdleTime, currentIdleTime);
                int kernel = CompareFileTime(lastKernelTime, currentKernelTime);
                int user = CompareFileTime(lastUserTime, currentUserTime);
                int sum = kernel + user;
                double cpuUsage = (sum- idle)*100.0 / sum;
                std::cout << "sum is " << sum << "cpu is " << cpuUsage << " idle time is " << idle <<std::endl;
                lastIdleTime = currentIdleTime;
                lastKernelTime = currentKernelTime;
                lastUserTime = currentUserTime;
        }
}
int mAIn()
{
        getSystemTimesExample();

        std::cout << "Hello World!\n";
}
回复

使用道具 举报

大神点评(1)

ArchieCari 2019-3-4 22:02:11 显示全部楼层
为什么会不一样,不应该啊
回复 支持 反对

使用道具 举报

说点什么

您需要登录后才可以回帖 登录 | 立即注册
HOT • 推荐