40

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

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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.
Where is the list of possible values to pass in to the PerformanceCounter constructor? I can't find it anywhere.
Can the loop be done on a separate thread and still yield meaningful results?
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.)
6

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

why is it not an option? Seems to be supported in .NET (granted I'm testing in .NET 6)
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).
4

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#?

2 Comments

how do you track process memory and CPU usage with WMI?
Yeah, your right. MSDN is running me in circles. I wind up at Performance Counters again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.