Can I use the "Idle" process to figure out why my processor utilization has been?

J

john

I don't want to know what the CPU utilization is right now. I want to
get the average utilization over the last, for example, hour. So I
came up with a method where I would get a Process object representing
the "Idle" process. I would figure out what percentage of time the
idle process has been running since my function last was called. Then
the average CPU utilization would be 100 - average idle percentage. I
figure out the average idle percentage by dividing the difference in
TotalProcessorTime by the difference in total time since the function
was called last. Here's the code

DateTime _oldTime;
TimeSpan _oldCPUUsage;

private void CPUUsage()
{
//Find out how much processor has been idle. Usage is 100% -
idle%.
DateTime newTime = DateTime.Now;
TimeSpan newCPUUsage = Process.GetProcessesByName
("Idle")[0].TotalProcessorTime;
double idlePercent =
(newCPUUsage.Subtract(_oldCPUUsage).TotalHours /
newTime.Subtract(_oldTime).TotalHours) * 100;

Debug.WriteLine((100.0 - idlePercent).ToString());
_oldCPUUsage = newCPUUsage;
_oldTime = newTime;
}

It seems to work great some of the time, but not all the time.
Sometimes my CPU usage (100.0 - idlePercent) ends up being negative or
really big (> 100000). So there's got to be something wrong in my
algorithm, but I don't know what. My thinking is that the "idle"
process might not always be an accurate way to get what I think it's
giving me. Any ideas?

Or is there a better way to do what I am trying to do?

thanks

John
 
M

Michael Giagnocavo [MVP]

Use the PerformanceCounters, so just like PerfMon, you can get accurate data
and average it out.
-mike
MVP
 
J

john

Use the PerformanceCounters, so just like PerfMon, you can get accurate data
and average it out.
-mike
MVP

If I use PerformanceCounters, can it return to me the average CPU
usage over the last hour? Or would I have to do a regular sample
(maybe once every 5 seconds) and then average the samples myself? If I
have to take samples and then average them, it will be somewhat
inaccurate (e.g. the usage could change quite a bit in the middle of
my samples). But with the method I proposed in my original post, it
will be completely accurate even if the function runs only once an
hour. The problem is that it occasionally gets crazy results.

thanks.
 
M

Michael Giagnocavo [MVP]

Those are some valid points. In the case that you get crazy results, why
not have it dump all the variables so you could see what went on?
-mike
MVP
 

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