Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the Number of CPU Cores via .NET/C#?

Tags:

c#

.net

cpu-cores

Is there a way via .NET/C# to find out the number of CPU cores?

PS This is a straight code question, not a "Should I use multi-threading?" question! :-)

like image 442
MrGreggles Avatar asked Oct 09 '09 06:10

MrGreggles


People also ask

How do I check number of CPU cores?

Press Ctrl + Shift + Esc to open Task Manager. Select the Performance tab to see how many cores and logical processors your PC has.

How do you find the number of physical cores?

Method 1: Check Number of CPU Cores Using Task Manager Press the Ctrl + Shift + Esc keys simultaneously to open the Task Manager. Go to the Performance tab and select CPU from the left column. You'll see the number of physical cores and logical processors on the bottom-right side.

How many cores do I have command line?

Check CPU cores from /proc/cpuinfo File in Linux Open the terminal and run this command: cat /proc/cpuinfo | grep “cpu cores” | uniq |sed -n 1p |awk '{print $4}'. It will list the number of CPU cores on your system.


1 Answers

There are several different pieces of information relating to processors that you could get:

  1. Number of physical processors
  2. Number of cores
  3. Number of logical processors.

These can all be different; in the case of a machine with 2 dual-core hyper-threading-enabled processors, there are 2 physical processors, 4 cores, and 8 logical processors.

The number of logical processors is available through the Environment class, but the other information is only available through WMI (and you may have to install some hotfixes or service packs to get it on some systems):

Make sure to add a reference in your project to System.Management.dll In .NET Core, this is available (for Windows only) as a NuGet package.

Physical Processors:

foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get()) {     Console.WriteLine("Number Of Physical Processors: {0} ", item["NumberOfProcessors"]); } 

Cores:

int coreCount = 0; foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get()) {     coreCount += int.Parse(item["NumberOfCores"].ToString()); } Console.WriteLine("Number Of Cores: {0}", coreCount); 

Logical Processors:

Console.WriteLine("Number Of Logical Processors: {0}", Environment.ProcessorCount); 

OR

foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get()) {     Console.WriteLine("Number Of Logical Processors: {0}", item["NumberOfLogicalProcessors"]); } 

Processors excluded from Windows:

You can also use Windows API calls in setupapi.dll to discover processors that have been excluded from Windows (e.g. through boot settings) and aren't detectable using the above means. The code below gives the total number of logical processors (I haven't been able to figure out how to differentiate physical from logical processors) that exist, including those that have been excluded from Windows:

static void Main(string[] args) {     int deviceCount = 0;     IntPtr deviceList = IntPtr.Zero;     // GUID for processor classid     Guid processorGuid = new Guid("{50127dc3-0f36-415e-a6cc-4cb3be910b65}");      try     {         // get a list of all processor devices         deviceList = SetupDiGetClassDevs(ref processorGuid, "ACPI", IntPtr.Zero, (int)DIGCF.PRESENT);         // attempt to process each item in the list         for (int deviceNumber = 0; ; deviceNumber++)         {             SP_DEVINFO_DATA deviceInfo = new SP_DEVINFO_DATA();             deviceInfo.cbSize = Marshal.SizeOf(deviceInfo);              // attempt to read the device info from the list, if this fails, we're at the end of the list             if (!SetupDiEnumDeviceInfo(deviceList, deviceNumber, ref deviceInfo))             {                 deviceCount = deviceNumber;                 break;             }         }     }     finally     {         if (deviceList != IntPtr.Zero) { SetupDiDestroyDeviceInfoList(deviceList); }     }     Console.WriteLine("Number of cores: {0}", deviceCount); }  [DllImport("setupapi.dll", SetLastError = true)] private static extern IntPtr SetupDiGetClassDevs(ref Guid ClassGuid,     [MarshalAs(UnmanagedType.LPStr)]String enumerator,     IntPtr hwndParent,     Int32 Flags);  [DllImport("setupapi.dll", SetLastError = true)] private static extern Int32 SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet);  [DllImport("setupapi.dll", SetLastError = true)] private static extern bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet,     Int32 MemberIndex,     ref SP_DEVINFO_DATA DeviceInterfaceData);  [StructLayout(LayoutKind.Sequential)] private struct SP_DEVINFO_DATA {     public int cbSize;     public Guid ClassGuid;     public uint DevInst;     public IntPtr Reserved; }  private enum DIGCF {     DEFAULT = 0x1,     PRESENT = 0x2,     ALLCLASSES = 0x4,     PROFILE = 0x8,     DEVICEINTERFACE = 0x10, } 
like image 116
Kevin Kibler Avatar answered Sep 28 '22 01:09

Kevin Kibler