Ho jun
Ho jun

Reputation: 93

Value of performance counter is strange

I used the following code to determine the total CPU usage of the computer.

private int getCPUUsage()
{
    PerformanceCounter cnt = new PerformanceCounter("Processor", "% Processor Time", "_Total");
    return (int)cnt.NextValue();
}

But, the CPU usage of the task manager is about 20%, but the output value of function is mostly 0, sometimes 100.
The odd point is that when I put a MessageBox in the middle of a function, the value of MessageBox is wrong, but the return value is correct.

private int getCPUUsage()
{
    PerformanceCounter cnt = new PerformanceCounter("Processor", "% Processor Time", "_Total");
    MessageBox.Show(cnt.NextValue().ToString()); //Just 0
    return (int)cnt.NextValue(); //Right Value
}

So I ran cnt.NextValue() twice instead of MessageBox, but the result was the same as the original code.
How do I get the PerformanceCounter's CPU usage normally?

Upvotes: 1

Views: 263

Answers (1)

Ryanas
Ryanas

Reputation: 1827

The first value will always be 0 because there's nothing to compare to.

You have to run it more times to get the comparison. 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.

Upvotes: 3

Related Questions