我坚持这个问题:我想计算使用特定应用程序的处理器百分比,在这种情况下,它具有 29 个 chrome 实例化。我对处理器如何消耗总共 29 个 chrome 实例感兴趣。我尝试过的代码:
private float GetCpuUsage(string ProcessName)
{
float cpuUsage = 0;
try
{
var ProcName = Process.GetProcessesByName(ProcessName);
var instances = new PerformanceCounter[ProcName.Length];
for (int i = 0; i < instances.Length; i++)
{
using (var TotalCpuUsage = new PerformanceCounter("Process", "% Processor Time", ProcName[i].ProcessName, true))
{
TotalCpuUsage.NextValue();
Thread.Sleep(1000); //for better aproximation cpu
double processNext = Math.Round((double)(TotalCpuUsage.NextValue() / Environment.ProcessorCount), 2);
Console.WriteLine("Processor Cpu:{0}, PidProcess:{1}", processNext, ProcName[i].Id);
cpuUsage += (float)processNext;
}
}
Console.WriteLine("Processor TotalCpu:{0}", cpuUsage);
return cpuUsage;
}
catch (Exception ex)
{
Message.Show(ex.Message + "\r\n" + ex.StackTrace);
return cpuUsage;
}
}
我有这些奇怪的结果:
Processor Cpu:6.51, PidProcess:18496
Processor Cpu:3.55, PidProcess:22056
Processor Cpu:20.54, PidProcess:16920
Processor Cpu:0, PidProcess:19420
Processor Cpu:0, PidProcess:7644
Processor Cpu:0, PidProcess:22500
Processor Cpu:14.07, PidProcess:19644
Processor Cpu:0, PidProcess:22004
Processor Cpu:3.55, PidProcess:23772
Processor Cpu:0, PidProcess:7948
Processor Cpu:6.91, PidProcess:22980
Processor Cpu:14.19, PidProcess:19464
Processor Cpu:0, PidProcess:18428
Processor Cpu:16, PidProcess:19408
Processor Cpu:0, PidProcess:20340
Processor Cpu:20.73, PidProcess:16660
Processor Cpu:9.37, PidProcess:7784
Processor Cpu:7.16, PidProcess:23984
Processor Cpu:0, PidProcess:8156
Processor Cpu:17.91, PidProcess:13272
Processor Cpu:10.1, PidProcess:20228
Processor Cpu:13.35, PidProcess:6568
Processor Cpu:3.55, PidProcess:6452
Processor Cpu:0, PidProcess:11668
Processor Cpu:0, PidProcess:16780
Processor Cpu:7.23, PidProcess:7036
Processor Cpu:0, PidProcess:19712
Processor Cpu:13.7, PidProcess:20316
Processor Cpu:3.45, PidProcess:20296
Processor TotalCpu:191.87
我可以通过什么方式解决这个问题?怎么做才能得到一些真正的结果