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 (9)

  1. Anonymous says:

    Whats the difference between this code and TASK Manager’s Process Tab’s "CPU Usage"??

  2. Anonymous says:

    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) ???

  3. Anonymous says:

    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.

  4. Anonymous says:

    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.)

  5. Anonymous says:

    I don’t see why you can’t just use Process.GetCurrentProcess().TotalProcessorTime

    What am I missing?

  6. Anonymous says:

    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

  7. BCL Team says:

    The code previously was incorrect and would always print 0. I update the code to correctly print out the percent CPU utilization.