Get multi-cell CPU usage in Visual C #

From time to time I searched about it and hoped that someone here could answer my question. Therefore, I am trying to find the best way to get the use of an average processor in 2 or 4 cores. I am currently using a performance counter, which, as far as I can tell, returns only one core. Ideally, I would like it to match or at least resemble the Usage panel in the task manager, and I looked through the WMI requests, but was hoping to get some clarification on the best approach. I am currently using i7, which has hyperthreading, i.e. It has "8" cores. Not sure if this matters a lot, but maybe. Thanks for any pointers

+4
source share
1 answer

Using Win32_PerfFormattedData_Counters_ProcessorInformation , you can use the PercentProcessorTime field, which will give instances of each core / thread on your system with the appropriate use.

I just tried this on my own and I have 8 control objects for my 8 threads.

 using System; using System.Management; using System.Windows.Forms; namespace WMISample { public class MyWMIQuery { public static void Main() { try { ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PerfFormattedData_Counters_ProcessorInformation"); foreach (ManagementObject queryObj in searcher.Get()) { Console.WriteLine("-----------------------------------"); Console.WriteLine("Win32_PerfFormattedData_Counters_ProcessorInformation instance"); Console.WriteLine("-----------------------------------"); Console.WriteLine("PercentProcessorTime: {0}", queryObj["PercentProcessorTime"]); } } catch (ManagementException e) { MessageBox.Show("An error occurred while querying for WMI data: " + e.Message); } } } } 

Update:

It was an easy lie, I had 10 copies. Their names were:

  • _Total
  • 0, _Total
  • 0.7
  • 0.6
  • 0.5

etc .. You should filter what you need with the where clause:

SELECT PercentProcessorTime FROM Win32_PerfFormattedData_Counters_ProcessorInformation WHERE NOT Name='_Total' AND NOT Name='0,_Total'

+6
source

All Articles