How to find the Number of CPU Cores via .NET/C#?
There are several different pieces of information relating to processors that you could get:
- Number of physical processors
- Number of cores
- 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,
}
How to get number of CPU's logical cores/threads in C#?
You can get number of logical processors through the Environment class
number of 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);
number of logical processors
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
Console.WriteLine("Number Of Logical Processors: {0}", item["NumberOfLogicalProcessors"]);
}
Environment.ProcessorCount
using System;
class Sample
{
public static void Main()
{
Console.WriteLine("The number of processors on this computer is {0}.",
Environment.ProcessorCount);
}
}
go through this link http://msdn.microsoft.com/en-us/library/system.environment.processorcount.aspx
Retrieving the number of physical core processors
You can use WMI to obtain the number of cores in the system. This similar question on stack overflow includes a code sample: --> How to find the Number of CPU Cores via .NET/C#?
An important point to keep in mind is that in certain systems this value may not be available; for example, on windows server 2003 you need to download a hotfix from Microsoft to get "NumberOfCores" to work.
Get total count of actual processor cores without Hyperthreading
I figured it out myself (using Linq). Alas, the code is not the fastest in speed terms. Reference System.Management
and you're good to go:
var processorCoreCount = new ManagementObjectSearcher("Select * from Win32_Processor").Get().Cast<ManagementBaseObject>().Sum(item => int.Parse(item["NumberOfCores"].ToString()));
Is there a way to reliably detect the total number of CPU cores?
See Detecting the number of processors
Alternatively, use the GetLogicalProcessorInformation()
Win32 API: http://msdn.microsoft.com/en-us/library/ms683194(VS.85).aspx
Correct way to get total number of logical cores from remote pc
This line
row["Cores"] = obj["NumberOfLogicalProcessors"].ToString();
is in error.
You need to add together all the cores found, not just use the last entry.
Related Topics
Make a Borderless Form Movable
Get the Correct Week Number of a Given Date
Reading an Integer from User Input
How to Perform a Left Outer Join Using Linq Extension Methods
How to Get C# Enum Description from Value
Why Would You Use String.Equals Over ==
How to Remove All Namespaces from Xml With C#
Json.Net Parser *Seems* to Be Double Serializing My Objects
How to Get Children of a Wpf Container by Type
Unit Testing Private Methods in C#
How to Strip Non-Ascii Characters from a String In C#
Make an Installation Program For C# Applications and Include .Net Framework Installer into the Setup