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.