31

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

Brad Rem
  • 5,902
  • 1
  • 23
  • 48
Louis Rhys
  • 30,777
  • 53
  • 137
  • 211

3 Answers3

54

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
  • 30,777
  • 53
  • 137
  • 211
  • 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
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
  • 168,684
  • 43
  • 314
  • 475
2

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,004
  • 3
  • 19
  • 37