Search code examples
.netwmicpuenvironment

Detecting the number of processors


How do you detect the number of physical processors/cores in .net?


Solution

  • System.Environment.ProcessorCount
    

    returns the number of logical processors

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

    For physical processor count you'd probably need to use WMI - the following metadata is supported in XP/Win2k3 upwards (Functionality enabled in SP's prior to Vista/Win2k8).

    Win32_ComputerSystem.NumberOfProcessors returns physical count

    Win32_ComputerSystem.NumberOfLogicalProcessors returns logical (duh!)

    Be cautious that HyperThreaded CPUs appear identical to multicore'd CPU's yet the performance characteristics are very different.

    To check for HT-enabled CPUs examine each instance of Win32_Processor and compare these two properties.

    Win32_Processor.NumberOfLogicalProcessors

    Win32_Processor.NumberOfCores

    On multicore systems these are typically the same the value.

    Also, be aware of systems that may have multiple Processor Groups, which is often seen on computers with a large number of processors. By default .Net will only using the first processor group - which means that by default, threads will utilize only CPUs from the first processor group, and Environment.ProcessorCount will return only the number of CPUs in this group. According to Alastair Maw's answer, this behavior can be changed by altering the app.config as follows:

    <configuration>
       <runtime>
          <Thread_UseAllCpuGroups enabled="true"/>
          <GCCpuGroup enabled="true"/>
          <gcServer enabled="true"/>
       </runtime>
    </configuration>