39

How can I use System.Diagnostics.PerformanceCounter to track the memory and CPU usage for a process?

Brad Rem
  • 6,036
  • 2
  • 25
  • 50
Louis Rhys
  • 34,517
  • 56
  • 153
  • 221

3 Answers3

61

For per process data:

Process p = /*get the desired process here*/;
PerformanceCounter ramCounter = new PerformanceCounter("Process", "Working Set", p.ProcessName);
PerformanceCounter cpuCounter = new PerformanceCounter("Process", "% Processor Time", p.ProcessName);
while (true)
{
    Thread.Sleep(500);
    double ram = ramCounter.NextValue();
    double cpu = cpuCounter.NextValue();
    Console.WriteLine("RAM: "+(ram/1024/1024)+" MB; CPU: "+(cpu)+" %");
}

Performance counter also has other counters than Working set and Processor time.

Louis Rhys
  • 34,517
  • 56
  • 153
  • 221
  • 6
    It should be noted that the Sleep is required, calling NextValue, then Sleeping for 500-100, then calling NextValue to get the actual value works, if you call NextValue first then use that value and continue to next process, it will always be 0 value for processor %, the RAM value works regardless. – ScottN Aug 24 '11 at 03:52
  • 2
    Where is the list of possible values to pass in to the PerformanceCounter constructor? I can't find it anywhere. – Patrick Szalapski Sep 10 '14 at 03:54
  • 1
    to retrieve the list of counters : https://msdn.microsoft.com/en-us/library/851sb1dy.aspx ; also a good article http://www.infoworld.com/article/3008626/application-development/how-to-work-with-performance-counters-in-c.html – Bernhard Oct 05 '16 at 10:31
  • Can the loop be done on a separate thread and still yield meaningful results? – ryanwebjackson Oct 04 '18 at 21:34
  • This is super-helpful. I've found in addition that in order to get a CPU utilization value similar to what's shown in Task Manager and Resource Monitor, you must divide the cpu counter by Environment.ProcessorCount. (Sorry, I appear to have closed the tab on which I found that hint... but sure do wish there was official documentation on this somewhere.) – ALEXintlsos Sep 27 '22 at 21:41
5

If you are using .NET Core, the System.Diagnostics.PerformanceCounter is not an option. Try this instead:

System.Diagnostics.Process p = System.Diagnostics.Process.GetCurrentProcess();
long ram = p.WorkingSet64;
Console.WriteLine($"RAM: {ram/1024/1024} MB");
tgolisch
  • 6,549
  • 3
  • 24
  • 42
3

I think you want Windows Management Instrumentation.

EDIT: See here:

Measure a process CPU and RAM usage

How to get the CPU Usage in C#?

Community
  • 1
  • 1
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501