我按照接受的答案Using PerformanceCounter to Track Memory and CPU Usage
但我发现结果与任务管理器中的值不同:
mic_on
代码是否正确?如何在任务管理器中获得完全相同的值?
答案 0 :(得分:2)
您的代码即将很好,但几乎无需改进:
"Process"-"% Processor Time"
始终返回系统中所有CPU的CPU使用率。所以返回值应该由Environment.ProcessorCount
分隔。这是任务管理器显示的实际值"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);
}