检测处理器数量

Pet*_*r C 28 .net environment cpu wmi

如何检测.net中的物理处理器/核心数?

ste*_*hbu 29

System.Environment.ProcessorCount
Run Code Online (Sandbox Code Playgroud)

返回逻辑处理器的数量

http://msdn.microsoft.com/en-us/library/system.environment.processorcount.aspx

对于物理处理器数量,您可能需要使用WMI - XP/Win2k3以上支持以下元数据(在Vista/Win2k8之前的SP中启用功能).

Win32_ComputerSystem.NumberOfProcessors返回物理计数

Win32_ComputerSystem.NumberOfLogicalProcessors返回逻辑(duh!)

要谨慎的是超线程CPU出现相同multicore'd CPU的但性能特点是非常不同的.

要检查启用HT的CPU,请检查Win32_Processor的每个实例并比较这两个属性.

Win32_Processor.NumberOfLogicalProcessors

Win32_Processor.NumberOfCores

在多核系统上,这些值通常是相同的.

此外,请注意可能具有多个处理器组的系统,这通常出现在具有大量处理器的计算机上.默认情况下.Net仅使用第一个处理器组 - 这意味着默认情况下,线程将仅使用来自第一个处理器组的CPU,并且Environment.ProcessorCount仅返回该组中的CPU数量.根据Alastair Maw的回答,可以通过更改app.config来更改此行为,如下所示:

<configuration>
   <runtime>
      <Thread_UseAllCpuGroups enabled="true"/>
      <GCCpuGroup enabled="true"/>
      <gcServer enabled="true"/>
   </runtime>
</configuration>
Run Code Online (Sandbox Code Playgroud)


Jes*_*cer 11

虽然Environment.ProcessorCount确实可以获得系统中虚拟处理器的数量,但这可能不是您的进程可用的处理器数量.我掀起了一个快速的小静态类/属性来得到这个:

using System;
using System.Diagnostics;

/// <summary>
/// Provides a single property which gets the number of processor threads
/// available to the currently executing process.
/// </summary>
internal static class ProcessInfo
{
    /// <summary>
    /// Gets the number of processors.
    /// </summary>
    /// <value>The number of processors.</value>
    internal static uint NumberOfProcessorThreads
    {
        get
        {
            uint processAffinityMask;

            using (var currentProcess = Process.GetCurrentProcess())
            {
                processAffinityMask = (uint)currentProcess.ProcessorAffinity;
            }

            const uint BitsPerByte = 8;
            var loop = BitsPerByte * sizeof(uint);
            uint result = 0;

            while (--loop > 0)
            {
                result += processAffinityMask & 1;
                processAffinityMask >>= 1;
            }

            return (result == 0) ? 1 : result;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 没有所有核心可用的+1可能发生在很多场景中,例如"web-garden"配置中的ASP.NET代码. (4认同)