Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the cpu performance counter kept reporting 0% cpu usage?

PerformanceCounter cpuload = new PerformanceCounter(); cpuload.CategoryName = "Processor"; cpuload.CounterName = "% Processor Time"; cpuload.InstanceName = "_Total"; Console.WriteLine(cpuload.NextValue() + "%"); 

The output is always 0%, while the cpuload.RawValue is like 736861484375 or so, what happened at NextValue()?

like image 846
smwikipedia Avatar asked Feb 02 '10 04:02

smwikipedia


People also ask

What are CPU performance counters?

The CPU performance counters are counting the number of instructions, clock ticks and multi counters ticks. They are used to measure the run-time of a c-function. The result is stored in a global variable. Copyright © Infineon Technologies AG 2020.

What is the use of performance counter?

Windows Performance Counters provide a high-level abstraction layer that provides a consistent interface for collecting various kinds of system data such as CPU, memory, and disk usage. System administrators often use performance counters to monitor systems for performance or behavior problems.


2 Answers

The first iteration of he counter will always be 0, because it has nothing to compare to the last value. Try this:

var cpuload = new PerformanceCounter("Processor", "% Processor Time", "_Total"); Console.WriteLine(cpuload.NextValue() + "%"); Console.WriteLine(cpuload.NextValue() + "%"); Console.WriteLine(cpuload.NextValue() + "%"); Console.WriteLine(cpuload.NextValue() + "%"); Console.WriteLine(cpuload.NextValue() + "%"); 

Then you should see some data coming out. It's made to be seen in a constant graph or updated scenario...that's why you don't come across this problem often.

Here's the MSDN reference:

The method nextValue() always returns a 0 value on the first call. So you have to call this method a second time.

like image 73
Nick Craver Avatar answered Sep 28 '22 06:09

Nick Craver


First retrieve first value (would be 0)

NextValue(); 

Then wait for 1000 milisec

Thread.Sleep(1000); 

Then retrieve second value which is the true cpu usage.

NextValue(); 

The code should look like this:

float perfCounterValue = perfCounter.NextValue();  //Thread has to sleep for at least 1 sec for accurate value. System.Threading.Thread.Sleep(1000);  perfCounterValue = perfCounter.NextValue();  Console.WriteLine("Value: {0}", perfCounterValue); 
like image 34
Max Avatar answered Sep 28 '22 06:09

Max