Home >Backend Development >C++ >How to Get the Number of CPU Cores in .NET/C#?
Retrieving CPU Core Count using .NET/C#
.NET/C# provides several methods for identifying the number of CPU cores available on a system. Here are a few approaches:
1. Physical Processors:
This method counts the number of physical processors installed.
<code class="language-csharp">foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get()) { Console.WriteLine($"Number of Physical Processors: {item["NumberOfProcessors"]}"); }</code>
2. Cores per Processor:
This approach sums the core count across all processors.
<code class="language-csharp">int totalCores = 0; foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get()) { totalCores += int.Parse(item["NumberOfCores"].ToString()); } Console.WriteLine($"Total Number of Cores: {totalCores}");</code>
3. Logical Processors:
This directly accesses the total number of logical processors (including hyperthreading).
<code class="language-csharp">Console.WriteLine($"Number of Logical Processors: {Environment.ProcessorCount}");</code>
4. Processors (excluding those hidden by Windows):
This method accounts for processors that might be excluded from standard Windows reporting. It requires using the Setup API.
<code class="language-csharp">int processorCount = 0; IntPtr deviceList = IntPtr.Zero; Guid processorGuid = new Guid("{50127dc3-0f36-415e-a6cc-4cb3be910b65}"); try { deviceList = SetupDiGetClassDevs(ref processorGuid, "ACPI", IntPtr.Zero, (int)DIGCF.PRESENT); for (int deviceNumber = 0; ; deviceNumber++) { SP_DEVINFO_DATA deviceInfo = new SP_DEVINFO_DATA(); deviceInfo.cbSize = Marshal.SizeOf(deviceInfo); if (!SetupDiEnumDeviceInfo(deviceList, deviceNumber, ref deviceInfo)) { processorCount = deviceNumber; break; } } } finally { if (deviceList != IntPtr.Zero) { SetupDiDestroyDeviceInfoList(deviceList); } } Console.WriteLine($"Number of Cores (including hidden): {processorCount}");</code>
Important Considerations:
System.Management.dll
in your project.The above is the detailed content of How to Get the Number of CPU Cores in .NET/C#?. For more information, please follow other related articles on the PHP Chinese website!