zoukankan      html  css  js  c++  java
  • 取得某个进程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;
    }
  • 相关阅读:
    Vue技巧小结(持续更新)
    Vue+Webpack常见问题(持续更新)
    webpack模块定义和使用的模式
    vue-cli笔记
    新浪微博怎么知道你没登录
    jquery页面水印插件,支持多行水印、行错开
    浏览器并发连接数(未完成)
    HTTP1.0 、1.1
    你总说时间很少
    看小说的这些年
  • 原文地址:https://www.cnblogs.com/zengqh/p/2479813.html
Copyright © 2011-2022 走看看