Search code examples
c++windowsperformancecounter

Issue with PDH Counter returning incorrect values after upgrading to Windows 11


I've encountered an issue with the PDH counter after updating my system from Windows 10 to Windows 11. I have a C++ program that monitors CPU usage and it was working perfectly on the previous version of Windows, but once I upgraded to Windows 11, the PDH counter began to return incorrect values. The code is as follows:

//Declare variables
double cpuUsage
PDH_HQUERY cpuQuery;
PDH_HCOUNTER cpuTotal;

//Initialize at the start
PdhOpenQuery(NULL, NULL, &cpuQuery);
PdhAddEnglishCounter(cpuQuery, L"\\Processor(_Total)\\% Processor Time", NULL, &cpuTotal);
PdhCollectQueryData(cpuQuery);

//Code to be called every second
PDH_FMT_COUNTERVALUE counterVal;
PdhCollectQueryData(cpuQuery);
PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal);
cpuUsage = counterVal.doubleValue;

Does anyone know if Windows 11 has made any changes that would affect this? If so, can someone suggest a workaround, solution, or perhaps a more straightforward method for monitoring CPU usage?

I tested the code on three separate computers and each system provided different CPU usage ranges: one returned between 0% and 0.2%, another returned between 300% and 400%, and the last one between 7% and 15%.

My expectation is that the CPU usage data my application retrieves should match with the CPU utilization percentages represented in the Windows 11 Task Manager, which typically ranges from 0% to 100%.

These inconsistencies are also found in the official PDH sample code provided by Microsoft: browsing-performance-counters


Solution

  • using "\\Processor Information(_Total)\\% Processor Utility" instead.