为什么我的性能计数器代码不起作用?

我正在尝试使用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是在项目中使用的macros来声明的。 在调用PdhGetRawCounterValue()之前,每个调用的状态都是ERROR_SUCCESS。 当我调用该函数时,结果是0xC0000BBC,在pdhmsg.h中定义为PDH_INVALID_HANDLE。 调用Sleep()的原因是这个页面说你需要为某些计数器读取两个样本,然后等待至less一秒。

难道我做错了什么?

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

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

而且看起来对PdhCloseQuery的调用也可能不应该传递参数的地址。

 status = PdhCloseQuery(query);