2010-11-01 54 views
2

我正在尝试使用Windows性能计数器来获取特定进程的虚拟字节使用情况。阅读%CPU占用率似乎比较简单,所以我想我会试着让它首先工作。为什么我的性能计数器代码不起作用?

在文件的顶部,我有这样的:

#include <pdh.h> 
#include <pdhmsg.h> 

然后在一个功能,我有这样的:

PDH_STATUS status = ERROR_SUCCESS; 

PDH_HQUERY query = NULL; 
status = PdhOpenQuery(
    NULL, 
    0, 
    &query); 
CHECK(status == ERROR_SUCCESS, L"Couldn't create query."); 

PDH_HCOUNTER counter = NULL; 
status = PdhAddCounter(query, L"\\Processor(_Total)\\% Processor Time", 0, &counter); 
CHECK(status == ERROR_SUCCESS, L"Couldn't add counter."); 

status = PdhCollectQueryData(query); 
CHECK(status == ERROR_SUCCESS, L"Couldn't collect query data."); 
Sleep(2000); 

status = PdhCollectQueryData(query); 
CHECK(status == ERROR_SUCCESS, L"Couldn't collect query data."); 
Sleep(2000); 

PDH_RAW_COUNTER rawValue; 
status = PdhGetRawCounterValue(&counter, NULL, &rawValue); 
CHECK(status == ERROR_SUCCESS, L"Couldn't get the raw counter value."); 

status = PdhCloseQuery(&query); 
CHECK(status == ERROR_SUCCESS, L"Couldn't close the query handle."); 

CHECK是用于该项目的断言宏。在调用PdhGetRawCounterValue()之前,每次调用时的状态为ERROR_SUCCESS。当我调用该函数时,结果是0xC0000BBC,它在pdhmsg.h中定义为PDH_INVALID_HANDLE。调用Sleep()的原因是this page表示您需要为某些计数器读取两个样本,并等待至少一秒之间。

我做错了什么?

回答

3

我认为你需要删除符号(不带计数器的地址):

status = PdhGetRawCounterValue(counter, NULL, &rawValue); 

它看起来像调用PdhCloseQuery也可能不应该是传递参数的地址。

status = PdhCloseQuery(query); 
相关问题