Home >Backend Development >C++ >How Can I Retrieve the CPU Core Count in .NET/C#?
Get the number of CPU cores in .NET/C#
Determining the number of CPU cores available to your application is critical to optimizing performance. In .NET/C#, there are multiple ways to extract this information:
1. Environment.ProcessorCount
This property provides the number of logical processors on the system. However, it does not differentiate between physical processors and hyper-threaded cores.
<code class="language-C#">Console.WriteLine("逻辑处理器数量: {0}", Environment.ProcessorCount);</code>
2. Win32_Processor
Using WMI (Windows Management Instrumentation) you can access more detailed information about the processor:
Physical Processor:
<code class="language-C#">foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get()) { Console.WriteLine("物理处理器数量: {0}", item["NumberOfProcessors"]); }</code>
Number of cores:
<code class="language-C#">int coreCount = 0; foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get()) { coreCount += int.Parse(item["NumberOfCores"].ToString()); } Console.WriteLine("核心数量: {0}", coreCount);</code>
3. Excluded processors
Additionally, you can use Windows API calls to discover excluded processors in Windows. The following code displays the total number of logical processors, including excluded processors:
<code class="language-C#">int deviceCount = 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)) { deviceCount = deviceNumber; break; } } } finally { if (deviceList != IntPtr.Zero) { SetupDiDestroyDeviceInfoList(deviceList); } } Console.WriteLine("核心数量: {0}", deviceCount);</code>
The above is the detailed content of How Can I Retrieve the CPU Core Count in .NET/C#?. For more information, please follow other related articles on the PHP Chinese website!