Reputation: 11304
For below Performance counter, I am always getting % Processor Time is 0, even my CPU shows 100% usage, what could be the reason?
PerformanceCounter pc = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);
Console.WriteLine(pc.NextValue());
Upvotes: 1
Views: 1159
Reputation: 31
If you try directly read total time you will always get 0, the reason being is that the PerformanceCounter object needs 2 values to give an accurate reading.
The method below returns an int representing the accurate % of CPU usage at that time.
while (true)
{
PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
float tempValue = cpuCounter.NextValue();
Thread.Sleep(1000);
Console.WriteLine(cpuCounter.NextValue());
}
Upvotes: 2
Reputation: 1499800
It's explained by the remarks in the NextValue()
documentation:
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 if you change your code to something like:
while (true)
{
Console.WriteLine(pc.NextValue());
Thread.Sleep(1000);
}
... then you'll see appropriate values.
Upvotes: 5