I stuck with this problem: I want to calculate what percentage of processor use a specific application , in this case that features 29 chrome instantiations . I am interested in how the processor consumes a total of 29 instantiations of chrome.The code I tried it:
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;
}
}
And I have these strange results:
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
In what way I could tackle this problem ?? What to do to get some real results
I think the issue here may be that you are not taking into account that your system has multiple cores. You will need to divide the percentages by the number of cores available on the system. Take a look at the link below. http://www.allenconway.net/2013/07/get-cpu-usage-across-all-cores-in-c.html