Windows下获取CPU使用率

xingyun86 2021-4-16 1300

Windows下获取CPU使用率

#pragma once
#include <winsock2.h>

class CCPUInfoMgr {
public:
    uint64_t DiffFileTime(FILETIME time1, FILETIME time2)
    {
        uint64_t a = (time1.dwHighDateTime << 32) | time1.dwLowDateTime;
        uint64_t b = (time2.dwHighDateTime << 32) | time2.dwLowDateTime;
        return   b - a;
    }

    CRITICAL_SECTION slock;

    double scpuuse = 0;

    void SetCpuUsage(double cpu)
    {
        EnterCriticalSection(&slock);
        scpuuse = cpu;
        LeaveCriticalSection(&slock);
    }

    double GetCpuUsage()
    {
        double cpu = 0;
        EnterCriticalSection(&slock);
        cpu = scpuuse;
        LeaveCriticalSection(&slock);
        return cpu;
    }

    static DWORD WINAPI   ThreadProc(LPVOID lpParam)
    {
        CCpuInfoMgr* thiz = (CCpuInfoMgr*)lpParam;
        int idle, kernel, user;
        FILETIME idleTime1, idleTime2;
        FILETIME kernelTime1, kernelTime2;
        FILETIME userTime1, userTime2;
        do
        {
            GetSystemTimes(&idleTime1, &kernelTime1, &userTime1);
            Sleep(1000);
            GetSystemTimes(&idleTime2, &kernelTime2, &userTime2);
            idle = (int)thiz->DiffFileTime(idleTime1, idleTime2);
            kernel = (int)thiz->DiffFileTime(kernelTime1, kernelTime2);
            user = (int)thiz->DiffFileTime(userTime1, userTime2);
            if (kernel + user == 0)
                thiz->SetCpuUsage(0.0);
            else
                thiz->SetCpuUsage(abs((kernel + user - idle) * 100 / (kernel + user)));//(总的时间-空闲时间)/总的时间=占用cpu的时间就是使用率
        } while (1);

    }
    BOOL GetCPUInfo()
    {
        BOOL bRet = FALSE;
        HANDLE m_hThread;

        InitializeCriticalSection(&slock);

        m_hThread = CreateThread(NULL, 0, &ThreadProc, this, 0, NULL);//创建新线程  

        do

        {

            printf("cpu useage: %.1f!\n", GetCpuUsage());

            Sleep(1000);

        } while (1);

        CloseHandle(m_hThread);

        DeleteCriticalSection(&slock);

        return bRet;
    }
    void Print()
    {
        
        std::cout << "==============" << std::endl;
    }
};


×
打赏作者
最新回复 (0)
查看全部
全部楼主
返回