0

There are a couple of questions here about how to monitor CPU usage, but I cannot get my code to display anything other than 0.

Can someone please take a look and let me know what I'm doing wrong?

PerformanceCounter perform = new PerformanceCounter("Processor", "% Processor Time", "_Total");
public string cpuTime()
{
      return perform.NextValue() + "%";
}
public void cpuUtilization()
{
}
public String getCPUUtilization()
{
      return cpuTime();
}
slugster
  • 49,403
  • 14
  • 95
  • 145
The Woo
  • 17,809
  • 26
  • 57
  • 71
  • 5
    Are you calling it more than once? `perform.NextValue()` requires two calls. The number it gives you is the result of `number of cycles executed by process between calls/total cycles executed between calls`. The first time you call it it gives you `0` then after that it starts giving you accurate numbers. See [this old answer of mine](http://stackoverflow.com/questions/8462331/i-need-to-call-accurate-cpu-usage-of-a-single-process/8462977#8462977) for more info – Scott Chamberlain Nov 27 '13 at 22:08
  • 1
    Also note that you need a minimum of 100ms between the two calls for it to work, otherwise you will only get results of 0% or 100%. – Scott Chamberlain Nov 27 '13 at 22:17

1 Answers1

0

A processor only ever does two things. It either executes code, running at full bore. Or it is halted by the operating system when it can't find any work to do, by far the most common case.

So to arrive at a % utilization, you need to find out what it is doing over an interval. One second is the common choice. Utilization is now the amount of time within that second that it was running vs the amount of time it was halted.

The interval is what is missing from your code. After you call your cpuTime() method, you have to wait until you call it again. So enough historical data was gathered. That requires a timer. The shorter you make the interval, the less reliable your measurement gets. Make it too short and you'll only ever get either 0 or 100%. Your current problem.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536