Search code examples
c#cpu-usageperformancecounter

I want to get CPU usage (all of core) every 1sec


First of all, I have been started to studying the C# from 8 months ago and I'm not good at English. So I'm sorry if I say something that you cannot understand.

Now, I'm developing the application with C# that get percentage of CPU usage. I want to get CPU usage that all of Cores every one sec. Then I used the PerformanceCounter Class and Processor Category. This is code I wrote.

    private void GetCpuUsageEvery1sec(object sender, ElapsedEventArgs e)
    {
        int getValue = 0;
        mProcessorCount = Environment.ProcessorCount;

        mPerformanceCounter.CategoryName = "Processor";
        mPerformanceCounter.CounterName = "% Processor Time";
        mPerformanceCounter.InstanceName = "_TOTAL";

        getValue = (int)Math.Truncate(mPerformanceCounter.NextValue());

        mProcessorCpuUsage[mProcessorCount] = getValue;   //I set TOTAL's usage in last of Array

        Console.WriteLine(DateTime.Now.ToString());
        Console.WriteLine("Core:TOTAL {0}%", mProcessorCpuUsage[mProcessorCount]);

        for (int count = 0; count < mProcessorCount; count++)
        {
            mPerformanceCounter.InstanceName = count.ToString();   //this code is case

            getValue = (int)Math.Truncate(mPerformanceCounter.NextValue());
            mProcessorCpuUsage[count] = getValue;
            Console.WriteLine("Core:{0} {1}%", count, mProcessorCpuUsage[count]);
        }

        Console.WriteLine();

    }

I wrote the Method with Timer Class that start GetCpuUsageEvery1sec Method as Event, too.

However, in the Processor category (or Processor Time Counter), this counter throw 0 if I change the InstanceName. So, I cannot get only 0 if I do the Method with Timer Class.

I think that if I want to get a correct CPU usage, I should make instances same at number of Core. (And many of user will use this application. So I cannot specify the number of Core in advance.)

In this situation, I cannot get other solution?


Solution

  • I'd advice you to use the WMI query:

    ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PerfFormattedData_PerfOS_Processor");
                var cpuTimes = searcher.Get()
                    .Cast<managementobject>()
                    .Select(mo => new
                    {
                        Name = mo["Name"],
                        Usage = mo["PercentProcessorTime"]
                    }
                    )
                    .ToList();
    

    Hook this one up with a timer and you'll be settled good, it is better then using a for loop for every core.