Using PerformanceCounter to track memory and CPU usage per process?
Asked Answered
P

3

39

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

Pegmatite answered 5/8, 2010 at 4:43 Comment(0)
P
62

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.

Pegmatite answered 23/8, 2010 at 6:46 Comment(5)
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.Grasmere
Where is the list of possible values to pass in to the PerformanceCounter constructor? I can't find it anywhere.Acetal
to retrieve the list of counters : msdn.microsoft.com/en-us/library/851sb1dy.aspx ; also a good article infoworld.com/article/3008626/application-development/…Estheresthesia
Can the loop be done on a separate thread and still yield meaningful results?Unproductive
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.)Elysha
P
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");
Pamplona answered 10/12, 2019 at 14:16 Comment(2)
why is it not an option? Seems to be supported in .NET (granted I'm testing in .NET 6)Antipyrine
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).Pamplona
M
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#?

Mispronounce answered 5/8, 2010 at 4:47 Comment(2)
how do you track process memory and CPU usage with WMI?Pegmatite
Yeah, your right. MSDN is running me in circles. I wind up at Performance Counters again.Mispronounce

© 2022 - 2024 — McMap. All rights reserved.