How can I use System.Diagnostics.PerformanceCounter to track the memory and CPU usage for a process?
3 Answers
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.
5 Comments
ScottN
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.
Patrick Szalapski
Where is the list of possible values to pass in to the PerformanceCounter constructor? I can't find it anywhere.
Bernhard
to retrieve the list of counters : msdn.microsoft.com/en-us/library/851sb1dy.aspx ; also a good article infoworld.com/article/3008626/application-development/…
ryanwebjackson
Can the loop be done on a separate thread and still yield meaningful results?
ALEXintlsos
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.)
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");
2 Comments
pushkin
why is it not an option? Seems to be supported in .NET (granted I'm testing in .NET 6)
tgolisch
Pushkin, you are correct. System.Diagnostics.PerformanceCounter was added in Dec 2023 as part of .net Platform Extensions 8.0. This answer was relevant before Dec 2023, or for anyone who doesn't use Platform Extensions 8.0 (or above).
I think you want Windows Management Instrumentation.
EDIT: See here:
2 Comments
Louis Rhys
how do you track process memory and CPU usage with WMI?
Robert Harvey
Yeah, your right. MSDN is running me in circles. I wind up at Performance Counters again.