如何使用System.Diagnostics.PerformanceCounter跟踪进程的内存和CPU使用情况?
答案 0 :(得分:46)
对于每个流程数据:
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)+" %");
}
性能计数器还有其他计数器,而不是工作集和处理器时间。
答案 1 :(得分:3)
答案 2 :(得分:0)
如果您使用的是.NET Core,则System.Diagnostics.PerformanceCounter
不是一个选择。尝试以下方法:
System.Diagnostics.Process p = System.Diagnostics.Process.GetCurrentProcess();
long ram = p.WorkingSet64;
Console.WriteLine($"RAM: {ram/1024/1024} MB");