取得某个进程CPU的占用率

/* percent = (user_time_diff + kernel_time_diff) * 100 / (cpu_num * system_time_diff) */

#include<windows.h>

#include<stdio.h>

#include <pdh.h>

#include <Tlhelp32.h>

int main()

{

    // Find the specified Process

    HANDLE hProcess = NULL;

    PROCESSENTRY32 pe = {sizeof(pe)};

    HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

    BOOL suc = Process32First(hSnapShot, &pe);



    while(suc)

    {

        hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, false, pe.th32ProcessID);

        if(hProcess != NULL)

        {

            if(strcmp(pe.szExeFile, "cpu_test.exe") == 0)

            {

                break;

            }

        }

        CloseHandle(hProcess);

        suc = Process32Next(hSnapShot, &pe);

    }

    // Got it

    if(suc)

    {

        ULARGE_INTEGER ulLastSysTime, ulCurSysTime;

        ULARGE_INTEGER ulStart, ulEnd, 

            ulLastProcKernelTime, ulLastProcUserTime,

            ulCurProcKernelTime, ulCurProcUserTime;

        ULARGE_INTEGER ulKernelTimeUsed ,ulUserTimeUsed, ulSysTimePast;

        SYSTEM_INFO si = {0};

        int iCpuUsage = 0;



        GetSystemInfo(&si);

        GetSystemTimeAsFileTime((PFILETIME)&ulLastSysTime);

        GetProcessTimes(hProcess, (PFILETIME)&ulStart, (PFILETIME)&ulEnd, 

            (PFILETIME)&ulLastProcKernelTime, (PFILETIME)&ulLastProcUserTime);



        while(1)

        {



            Sleep(1000);



            GetProcessTimes(hProcess, (PFILETIME)&ulStart, (PFILETIME)&ulEnd, 

                (PFILETIME)&ulCurProcKernelTime, (PFILETIME)&ulCurProcUserTime);

            GetSystemTimeAsFileTime((PFILETIME)&ulCurSysTime);



            ulKernelTimeUsed.QuadPart = ulCurProcKernelTime.QuadPart - ulLastProcKernelTime.QuadPart;

            ulUserTimeUsed.QuadPart = ulCurProcUserTime.QuadPart - ulLastProcUserTime.QuadPart;

            ulSysTimePast.QuadPart = ulCurSysTime.QuadPart - ulLastSysTime.QuadPart;



            iCpuUsage = (

                (ulKernelTimeUsed.QuadPart + ulUserTimeUsed.QuadPart)*100 /  

                                (float)(si.dwNumberOfProcessors*ulSysTimePast.QuadPart)) + 0.5f

                ;



            printf("\rThe Process use %3d%%", iCpuUsage);



            ulLastSysTime = ulCurSysTime;

            ulLastProcKernelTime = ulCurProcKernelTime;

            ulLastProcUserTime = ulCurProcUserTime;

        }

    }

    return 0;

}

你可能感兴趣的:(cpu)