如何获得超过2个内核的CPU使用率?

我试着让我的程序CPU使用量除以核心。 现在我使用PerformanceCounter并在0和1之间更改InstanceName我有来自2个核心的数据。

PerformanceCounter pc0 = new PerformanceCounter("Processor", "% Processor Time", "0"); PerformanceCounter pc1 = new PerformanceCounter("Processor", "% Processor Time", "1"); 

如何获得第3,第4核等的核心使用?

有人能帮帮我吗?

谢谢

我之前没有使用过PerformanceCounter,但这样做有什么问题吗?

 PerformanceCounter pc0 = new PerformanceCounter("Processor", "% Processor Time", "0"); PerformanceCounter pc1 = new PerformanceCounter("Processor", "% Processor Time", "1"); PerformanceCounter pc2 = new PerformanceCounter("Processor", "% Processor Time", "2"); PerformanceCounter pc3 = new PerformanceCounter("Processor", "% Processor Time", "3"); 

我怀疑你真正问的是“ 我如何计算核心数 ?”。 此代码将计算核心数,然后根据该代码创建性能计数器。

  int coreCount = 0; foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get()) { coreCount += int.Parse(item["NumberOfCores"].ToString()); } PerformanceCounter[] pc = new PerformanceCounter[coreCount]; for (int i = 0; i < coreCount; i++) { pc[i] = new PerformanceCounter("Processor", "% Processor Time", i.ToString()); Console.WriteLine(pc[i].CounterName); } 

这可能是一个老问题,但对于寻找不同解决方案的其他人来说,为什么不使用System.Environment?

  public static List GetPerformanceCounters() { List performanceCounters = new List(); int procCount = System.Environment.ProcessorCount; for (int i = 0; i < procCount; i++) { System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", i.ToString()); performanceCounters.Add(pc); } return performanceCounters; } 

编辑:我注意到这只返回逻辑处理器的数量,而不是实际的核心数量。

这样的事情也应该适合您的要求

  public List GetServerStatus() { List cpuStatus = new List(); ObjectQuery wmicpus = new WqlObjectQuery("SELECT * FROM Win32_Processor"); ManagementObjectSearcher cpus = new ManagementObjectSearcher(wmicpus); try { int coreCount = 0; int totusage = 0; foreach (ManagementObject cpu in cpus.Get()) { //cpuStatus.Add(cpu["DeviceId"] + " = " + cpu["LoadPercentage"]); coreCount += 1; totusage += Convert.ToInt32(cpu["LoadPercentage"]); } if (coreCount > 1) { double ActUtiFloat = totusage / coreCount; int ActUti = Convert.ToInt32(Math.Round(ActUtiFloat)); //Utilisation = ActUti + "%"; cpuStatus.Add("CPU = " + ActUti); } else { cpuStatus.Add("CPU = " + totusage); } } catch (Exception ex) { throw ex; } finally { cpus.Dispose(); } return cpuStatus; } 
 foreach (var item in new System.Management.ManagementObjectSearcher("Select NumberOfLogicalProcessors from Win32_Processor").Get()) { coreCount += int.Parse(item["NumberOfLogicalProcessors"].ToString()); } PerformanceCounter[] pc = new PerformanceCounter[coreCount]; for (int i = 0; i < coreCount; i++) { pc[i] = new PerformanceCounter("Processor", "% Processor Time", i.ToString()); }