麦克雷 Mavom.cn

标题: GetSystemTimes来获取CPU的使用率和task manager结... [打印本页]

作者: Michaelmisy    时间: 2019-3-4 22:01
标题: 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";
}
作者: ArchieCari    时间: 2019-3-4 22:02
为什么会不一样,不应该啊




欢迎光临 麦克雷 Mavom.cn (http://www.mavom.cn/) Powered by Discuz! X3.5