我正在尝试使用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表示您需要读取一些计数器的两个样本,然后在它们之间至少等待一秒钟。
难道我做错了什么?
最佳答案
我认为您需要删除“&”号(不要使用柜台的地址):
status = PdhGetRawCounterValue(counter, NULL, &rawValue);
而且看起来对PdhCloseQuery的调用也可能不应该传递参数的地址。
status = PdhCloseQuery(query);