简体   繁体   English

在Visual C#中获取CPU多核使用情况

[英]Get CPU Multi-Core Usage in Visual C#

been searching around for this for a while, and hoping someone here can answer my question. 一直在寻找这个问题,希望这里有人可以回答我的问题。 So I am trying to find the best way to get the average CPU usage of 2 or 4 cores. 因此,我正在尝试找到获得2个或4个内核的平均 CPU使用率的最佳方法。 Currently I am using a Performance Counter which so far as I can tell, only returns the usage of a single core. 目前,我正在使用性能计数器,据我所知,该计数器仅返回单个内核的使用情况。 Ideally I would like it to match or at least resemble the Usage bar in Task Manager, and I have looked into WMI queries but was hoping to get some clarification on the best approach. 理想情况下,我希望它匹配或至少类似于“任务管理器”中的“使用情况”栏,我已经研究了WMI查询,但希望对最佳方法进行一些说明。 I am currently using an i7, which has hyperthreading, ie has "8" cores. 我当前正在使用具有超线程功能的i7,即具有“ 8”个内核。 Not sure if this makes much difference, but though it might. 不知道这是否有很大的区别,但可能会有所不同。 Thanks for any pointers 谢谢你的指导

Using Win32_PerfFormattedData_Counters_ProcessorInformation , you can use the field PercentProcessorTime which will give instances of every core/thread on your system with its respective usage. 使用Win32_PerfFormattedData_Counters_ProcessorInformation ,您可以使用PercentProcessorTime字段,该字段将提供系统上每个核心/线程的实例及其各自的用法。

I just tried this on mine, and I got 8 Management Objects for my 8 threads. 我只是在我的机器上尝试过,我的8个线程有8个管理对象。

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: 更新:

That was a slight lie, I got 10 instances. 那是一个小谎言,我有10个实例。 Their names were: 他们的名字是:

  1. _Total _总
  2. 0,_Total 0,_总计
  3. 0,7 0,7
  4. 0,6 0,6
  5. 0,5 0,5

etc. You should filter out what you need with a where clause: 等等。您应该使用where子句过滤掉所需的内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM