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表示您需要爲某些計數器讀取兩個樣本,並等待至少一秒之間。
我做錯了什麼?