Udostępnij za pośrednictwem


How to find CPU usage of a process? [Ravi Krishnaswamy]

I’ve seen this question come up a few times and the solution is hard to infer, especially given that the logical place you go to, the Process class, doesn’t have a property to reveal this information. We could look into adding it to Process class at some point.

 

Win32 reveals this information via a performance counter. You can query the “% Processor time” windows counter for a process that you are interested in as follows:

 

foreach (Process proc in Process.GetProcesses()) {
using (PerformanceCounter pcProcess = new PerformanceCounter("Process", "% Processor Time", proc.ProcessName)) {
pcProcess.NextValue();
System.Threading.Thread.Sleep(1000);
Console.WriteLine("Process:{0} CPU% {1}", proc.ProcessName, pcProcess.NextValue());
}
}

 

For an explanation on why two calls to NextValue are necessary and why there must we must wait between them see Ryan's How to Read Performance Counters blog entry.

Comments

  • Anonymous
    June 06, 2006
    Whats the difference between this code and TASK Manager's Process Tab's "CPU Usage"??
  • Anonymous
    June 06, 2006
    How could you make this code to work when you have more than one process with the same ProcessName (10 instances of some text editor for exemple) ???
  • Anonymous
    June 07, 2006
    It seems that you haven't read the previous post on this blog.

    Ryan explained that you need to call .NextValue() twice, preferably with about a second interval in order to get a correct reading.
  • Anonymous
    June 07, 2006
    Um....how do you find this in pure .net with no windows calls?(the project i am working on needs no platform specific code in it.)
  • Anonymous
    June 07, 2006
    I don't see why you can't just use Process.GetCurrentProcess().TotalProcessorTime

    What am I missing?

  • Anonymous
    June 14, 2006
    Hi,

    Here is an article and source code that show how to retreive:
    - processor usage
    - network usage
    - memory usage

    http://devauthority.com/blogs/krys/archive/2006/06/13/PerformanceMonitoring.aspx

    It is a very simple class to analyse the whole computer performance
  • Anonymous
    June 22, 2006
    The code previously was incorrect and would always print 0. I update the code to correctly print out the percent CPU utilization.
  • Anonymous
    June 08, 2009
    PingBack from http://insomniacuresite.info/story.php?id=7638