当前位置导航:炫浪网>>网络学院>>编程开发>>C++教程>>C++进阶与实例

C++实现提取进程的CPU占用率

    在开发过程中,有时候我们需要调用特定进程的CPU占有率,以此来测试程序的可靠性,及资源占用等等,今天给大家共享一段通过C++实现的代码。

 #include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include <pdh.h>
#pragma comment ( lib , \"Pdh.lib\" )
#define MAXPATH 80
int __cdecl _tmain (int argc, TCHAR **argv)
{
  HQUERY          hQuery;
  HCOUNTER        *pCounterHandle;
  PDH_STATUS      pdhStatus;
  PDH_FMT_COUNTERVALUE  fmtValue;
  DWORD          ctrType;
  CHAR            szPathBuffer[MAXPATH] = {’\\0’};
  int            nRetCode = 0;
  // Open the query object.
  pdhStatus = PdhOpenQuery (0, 0, &hQuery);

  pCounterHandle = (HCOUNTER *)GlobalAlloc(GPTR, sizeof(HCOUNTER));

/*
\\\\Processor(_Total)\\\\% Processor Time CPU使用率
\\\\System\\\\Processes 当前系统进程数
\\\\System\\\\Threads 当前系统线程数
\\\\Memory\\\\Commit Limit 总共内存数K (包括虚拟内存)
\\\\Memory\\\\Committed Bytes 已用内存数K (包括虚拟内存)
\\\\TCP\\\\Connections Active 系统中已建立的 TCP连接个数
\\\\其它Object Items 可以利用PdhEnumObjects()和PdhEnumObjectItems()得到

*/
 // strcat(szPathBuffer,\"\\\\System\\\\Processes\");

//  pdhStatus = PdhAddCounter (hQuery,  szPathBuffer,  0,  pCounterHandle);
  //得到QQ进程的CPU占用率,这句出错
 pdhStatus = PdhAddCounter(hQuery,\"\\\\Process(QQ)\\\\% Processor Time\",0,pCounterHandle);
  // \"Prime\" counters that need two values to display a
  //  formatted value.
  pdhStatus = PdhCollectQueryData (hQuery);

  // Get the current value of this counter.
  pdhStatus = PdhGetFormattedCounterValue (*pCounterHandle, [Page]
                                              PDH_FMT_DOUBLE,
                                              &ctrType,
                                              &fmtValue);


    //fmtValue.doubleValue为所要的结果
    if (pdhStatus == ERROR_SUCCESS) {
        printf (TEXT(\",\\\"%.20g\\\"\\n\"), fmtValue.doubleValue);
    }
else {
    // Print the error value.
        printf (TEXT(\"error.\\\"-1\\\"\"));
  }

  // Close the query.
  pdhStatus = PdhCloseQuery (hQuery);

  return nRetCode;
}

相关内容
赞助商链接