PerformanceCounter: Only 0% or 100% when get % Processor Time

C

Chris

I'm trying to do something really easy: just get the % CPU load. However, I
just get mostly 0's sprinkled with an occasional 100. I poked around on
the web for info, but all the stuff I found (I think) does what I have
below. Am I blanking out on something here?

Getting the available RAM works fine.

Code example below:

using System;
using System.Diagnostics;

namespace PerfMon
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
//Create CPU counter
PerformanceCounter cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";

//Create RAM counter
//PerformanceCounter ramCounter = new PerformanceCounter();
//ramCounter.CategoryName = "Memory";
//ramCounter.CounterName = "Available MBytes";

//Display counter
int i;
for (i=0;i<100;i++)
{
Console.WriteLine(cpuCounter.NextValue().ToString());
}

Console.ReadLine();
}
}
}
 
W

Willy Denoyette [MVP]

Chris wrote:
|| I'm trying to do something really easy: just get the % CPU load.
|| However, I just get mostly 0's sprinkled with an occasional 100. I
|| poked around on the web for info, but all the stuff I found (I
|| think) does what I have below. Am I blanking out on something here?
||
|| Getting the available RAM works fine.

Available RAM is a static value, CPU usage is dynamic you shouldn't read it in a tight loop, insert a sleep period of let's say 1
sec. to allow the OS to update the counter, and look for yourself.

|| for (i=0;i<100;i++)
|| {
|| Console.WriteLine(cpuCounter.NextValue().ToString());
System.Threading.Thread.Sleep(1000);
|| }
||
|| Console.ReadLine();
|| }
|| }
|| }

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