【问题标题】:C# Why my performance monitoring value is not exactly same value in Task Manager?C# 为什么我的性能监控值与任务管理器中的值不完全相同?
【发布时间】:2018-08-01 05:55:45
【问题描述】:

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

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

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) + " %");
 }

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

【问题讨论】:

    标签: c# performance


    【解决方案1】:

    您的代码即将完成,但需要一点改进:

    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"

    最终代码:

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

    【讨论】:

    • 非常感谢安东!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 2019-02-04
    • 1970-01-01
    • 2013-11-07
    • 2010-09-07
    相关资源
    最近更新 更多