Home > Backend Development > C++ > How to Determine the Number of Physical, Logical, and Available CPU Cores in .NET/C#?

How to Determine the Number of Physical, Logical, and Available CPU Cores in .NET/C#?

Mary-Kate Olsen
Release: 2025-01-18 20:12:12
Original
256 people have browsed it

How to Determine the Number of Physical, Logical, and Available CPU Cores in .NET/C#?

Use .NET/C# to detect the number of CPU cores

With the increasing popularity of multi-processing, it is crucial to determine the number of CPU cores for optimal performance. In .NET/C#, there are several ways to access this information:

Physical Processor

The number of physical processors can be retrieved using the following code:

<code class="language-csharp">foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
    Console.WriteLine("物理处理器数量:{0}", item["NumberOfProcessors"]);
}</code>
Copy after login

Kernel

To determine the number of cores, execute the following code:

<code class="language-csharp">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>
Copy after login

Logical Processor

The number of logical processors (often called hyperthreads) can be obtained using either of the following codes:

<code class="language-csharp">Console.WriteLine("逻辑处理器数量:{0}", Environment.ProcessorCount);</code>
Copy after login
<code class="language-csharp">foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
    Console.WriteLine("逻辑处理器数量:{0}", item["NumberOfLogicalProcessors"]);
}</code>
Copy after login

Excluded Processors

In some Windows configurations, specific processors may be excluded from detection. To do this you can use the Windows API call found in setupapi.dll:

<code class="language-csharp">static void Main(string[] args)
{
    int deviceCount = 0;
    IntPtr deviceList = IntPtr.Zero;

    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);
}

[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,
}

private static readonly Guid processorGuid = new Guid("{4d36e968-e325-11ce-bfc1-08002be10318}");</code>
Copy after login

The above is the detailed content of How to Determine the Number of Physical, Logical, and Available CPU Cores in .NET/C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template