1

I follow the accepted answer Using PerformanceCounter to Track Memory and CPU Usage

but I've found that the result is not same value in Task Manager:

enter image description here

var processName = Process.GetCurrentProcess().ProcessName;
PerformanceCounter ramCounter = new PerformanceCounter("Process", "Working Set", processName);
PerformanceCounter cpuCounter = new PerformanceCounter("Process", "% Processor Time", processName);
while (true)
{
    Thread.Sleep(500);
    double ram = ramCounter.NextValue();
    double cpu = cpuCounter.NextValue();
    Console.WriteLine("RAM: " + (ram / 1024 / 1024) + " MB; CPU: " + (cpu) + " %");
 }

Is the code correct? How can I get the exactly same value in Task Manager?

Oh My Dog
  • 781
  • 13
  • 32

1 Answers1

2

Your code is about to be good but need little improvements:

  1. "Process"-"% Processor Time" is always return CPU usage across all CPUs in the system. So returning value should be devided by Environment.ProcessorCount. Thats the actual value the Task Manager displays
  2. As Hans Passant said in this answer How to calculate private working set (memory)? Task Manager actually use "Process", "Working Set - Private" but not "Process"-"Working Set"

Final code:

        var processName = Process.GetCurrentProcess().ProcessName;
        PerformanceCounter ramCounter = new PerformanceCounter("Process", "Working Set - Private", processName);
        PerformanceCounter cpuCounter = new PerformanceCounter("Process", "% Processor Time", processName);

        while (true)
        {
            double ram = ramCounter.NextValue();
            double cpu = cpuCounter.NextValue() / Environment.ProcessorCount;

            Console.Clear();
            Console.WriteLine("RAM: "
                              + (ram / 1024).ToString("N0") + " KB; CPU: "
                              + cpu.ToString("N1") + " %;");

            Thread.Sleep(500);
        }
Anton Semenov
  • 6,227
  • 5
  • 41
  • 69