2

I have this code:

using (PerformanceCounter pfc = new PerformanceCounter("Processor", "% Processor Time", "_Total"))    
    return pfc.NextValue();

This always returns 0, even when the total CPU usage is not zero, and this corresponding counter when viewed in Performance Monitor is also not 0.

Why? What do I need to do to simply return total CPU usage?

This is a Windows 8.1 virtual machine.

Ryan Ries
  • 2,381
  • 1
  • 24
  • 33

1 Answers1

7

From MSDN:

If the calculated value of a counter depends on two counter reads, the first read operation returns 0.0. Resetting the performance counter properties to specify a different counter is equivalent to creating a new performance counter, and the first read operation using the new properties returns 0.0. The recommended delay time between calls to the NextValue method is one second, to allow the counter to perform the next incremental read.

So from that, I'd say the calculated value of the "% Processor Time" counter depends on two counter reads, so the first you're seeing is 0.0, per the docs.

I tested it using their suggestion of waiting a second between reads. I got 0.0 every time on the first read, but then positive values afterwards.

using (PerformanceCounter pfc = new PerformanceCounter("Processor", "% Processor Time", "_Total"))
{
    MessageBox.Show(pfc.NextValue().ToString());
    Thread.Sleep(1000);
    MessageBox.Show(pfc.NextValue().ToString());
    Thread.Sleep(1000);
    MessageBox.Show(pfc.NextValue().ToString());
}
Grant Winney
  • 65,241
  • 13
  • 115
  • 165