C# Calculate CPU usage for one process with multiple instances

1.4k views Asked by At

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

2

There are 2 answers

0
Brian Grayson On

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

0
cogumel0 On

I know this is a slightly old question, but I'd just like to add that there's a fundamental flaw in this approach.

The CPU usage is calculated using a time slice. In the case of the code above, it's calculated over the period of a second (same as Task Manager uses for example, so nothing wrong there).

However, you're creating a PerformanceCounter instance per process and you're pretty much only using a single instance at a time.

In real terms what this means is... you query process (chrome) at 00:00 (mm:ss) and again at 00:01, then you query (chrome#1) at 00:01 and again at 00:02, (chrome#2) at 00:02 and again at 00:03 ... etc

So it is entirely possible that when you queried (chrome) it was using 100% CPU, but a second later when you query (chrome#1) the former is now using 0% CPU and the latter is now using 100%, so when you add them up you get 200% CPU usage.

You need to query all processes at the same time to get an accurate representation.