Getting accurate CPU usage %

G

Guest

I'm trying to write a c# class that will outprint the cpu use to the console
(console.writeline). I basically copied the msdn supplied code, but what
prints out is either 0%, 100%, or 51.02...%, every time. If I make a GUI for
the app, it displays the correct % in the GUI display, and the debug console
- but the console app never displays the right %. Any ideas? This is the msdn
example - all I added to mine was the outprint to the console.

<code>
private static PerformanceCounter _cpuCounter;
private static float CpuUsage
{
get
{
if (_cpuCounter == null)
{
_cpuCounter = new PerformanceCounter(
"Processor", "% Processor Time", "_Total", true);
}
return _cpuCounter.NextValue();
}
}
</code
 
W

Willy Denoyette [MVP]

J B said:
I'm trying to write a c# class that will outprint the cpu use to the
console
(console.writeline). I basically copied the msdn supplied code, but what
prints out is either 0%, 100%, or 51.02...%, every time. If I make a GUI
for
the app, it displays the correct % in the GUI display, and the debug
console
- but the console app never displays the right %. Any ideas? This is the
msdn
example - all I added to mine was the outprint to the console.

<code>
private static PerformanceCounter _cpuCounter;
private static float CpuUsage
{
get
{
if (_cpuCounter == null)
{
_cpuCounter = new PerformanceCounter(
"Processor", "% Processor Time", "_Total", true);
}
return _cpuCounter.NextValue();
}
}
</code

What makes you think the values are incorrect? The value returned is the
actual value of the counter, the time you read the counter isn't the same as
the moment perfmon reads the value, so don't expect these to be the same.

Willy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top