I am trying to use the Windows performance counters to get the virtual bytes usage of a specific process. It seemed simpler to read the % CPU usage, so I thought I would try to get that to work first.
At the top of the file, I have this:
#include <pdh.h>
#include <pdhmsg.h>
Then in a function, I have this:
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 is macro that is used on the project to assert. The status is ERROR_SUCCESS at every call until the call to PdhGetRawCounterValue(). When I call that function, the result is 0xC0000BBC which is defined in pdhmsg.h as PDH_INVALID_HANDLE. The reason for the call to Sleep() is that this page says you need to read two samples for some counters and wait at least one second in between.
Am I doing something wrong?
I think you need to remove the ampersand (don’t take the address of counter):
And it looks like the call to PdhCloseQuery also should probably not be passing the address of the parameter.