如何使用System.Diagnostics.PerformanceCounter跟踪进程的内存和CPU使用率?

最佳答案

对于每个过程数据:

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

性能计数器还具有“工作集”和“处理器时间”以外的其他计数器。

10-01 01:44