C++ Windows 获取CPU利用率【转】

原文:http://blog.csdn.net/maoxing63570/article/details/6919599

#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include <pdh.h>
#include <pdhmsg.h>
#pragma comment(lib, "pdh.lib")
#define COUNT_INTERVAL 1000
const TCHAR *pszPathBuff=_T("\\Processor(_Total)\\% Processor Time");
//% Processor Time 指处理器用来执行非闲置线程时间的百分比。
//计算方法是,测量范例间隔内非闲置线程活动的时间,用范例间隔减去该值。
//(每台处理器有一个闲置线程,该线程在没有其他线程可以运行时消耗周期)。
//这个计数器是处理器活动的主要说明器,显示在范例间隔时所观察的繁忙时间平均百分比。
//这个值是用 100% 减去该服务不活动的时间计算出来的。

int main()
{
    HQUERY          hQuery;
    HCOUNTER        hCounter;
    PDH_STATUS      pdhStatus;
    PDH_FMT_COUNTERVALUE   fmtValue;
    DWORD           ctrType;
    SYSTEMTIME      stSampleTime;
    
    __try
    {
        pdhStatus = PdhOpenQuery(NULL, NULL, &hQuery);
        if (ERROR_SUCCESS != pdhStatus)
        {
            _tprintf(TEXT("PdhOpenQuery failed with %ld.\n"), pdhStatus);
            __leave;
        }
        
        pdhStatus = PdhAddCounter (hQuery,
            pszPathBuff, 
            0, 
            &hCounter);
        if (ERROR_SUCCESS != pdhStatus)
        {
            _tprintf(TEXT("PdhBrowseCounters failed with 0x%x.\n"), pdhStatus);
            __leave;
        }
        
        pdhStatus = PdhCollectQueryData (hQuery);
        if (ERROR_SUCCESS != pdhStatus)
        {
            _tprintf(TEXT("PdhCollectQueryData failed with 0x%x.\n"), pdhStatus);
            __leave;
        }
        
        while (!_kbhit()) 
        {
            
            Sleep(COUNT_INTERVAL);
            GetLocalTime (&stSampleTime);
            pdhStatus = PdhCollectQueryData (hQuery);
            _tprintf (
                TEXT("\n\"%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d.%3.3d\""),
                stSampleTime.wMonth, 
                stSampleTime.wDay, 
                stSampleTime.wYear,
                stSampleTime.wHour, 
                stSampleTime.wMinute, 
                stSampleTime.wSecond,
                stSampleTime.wMilliseconds);
            
            pdhStatus = PdhGetFormattedCounterValue (hCounter,
                PDH_FMT_DOUBLE,
                &ctrType,
                &fmtValue);
            
            if (pdhStatus == ERROR_SUCCESS)
            {
                _tprintf (TEXT(",\"%.20g\""), fmtValue.doubleValue);
            }
            else
            {
                _tprintf(TEXT("\nPdhGetFormattedCounterValue failed with 0x%x.\n"), pdhStatus);
                __leave;
            }
        }
    }
    __finally
    {
        if (hQuery)
            PdhCloseQuery (hQuery);
    }
    
    
    return pdhStatus;
}

 

posted @ 2013-04-24 15:43  Leo Forest  阅读(1560)  评论(0编辑  收藏  举报