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

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

Rate This
  • Comments 9

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.

 

  • Whats the difference between this code and TASK Manager's Process Tab's "CPU Usage"??
  • 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) ???
  • 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.
  • 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.)
  • I don't see why you can't just use Process.GetCurrentProcess().TotalProcessorTime

    What am I missing?

  • 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
  • The code previously was incorrect and would always print 0. I update the code to correctly print out the percent CPU utilization.
  • PingBack from http://insomniacuresite.info/story.php?id=7638

Page 1 of 1 (9 items)