C#为什么我的性能监控值与任务管理器中的值不完全相同?

时间:2018-02-21 15:23:33

标签: c# performance

我按照接受的答案Using PerformanceCounter to Track Memory and CPU Usage

但我发现结果与任务管理器中的值不同:

enter image description here

mic_on

代码是否正确?如何在任务管理器中获得完全相同的值?

1 个答案:

答案 0 :(得分:2)

您的代码即将很好,但几乎无需改进:

  1. "Process"-"% Processor Time"始终返回系统中所有CPU的CPU使用率。所以返回值应该由Environment.ProcessorCount分隔。这是任务管理器显示的实际值
  2. 正如Hans Passant在这个回答中所说How to calculate private working set (memory)? 任务管理器实际上使用"Process", "Working Set - Private"但不是 "Process"-"Working Set"
  3. 最终代码:

            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);
            }