首页 >后端开发 >C++ >如何确定 .NET/C# 中物理、逻辑和可用 CPU 核心的数量?

如何确定 .NET/C# 中物理、逻辑和可用 CPU 核心的数量?

Mary-Kate Olsen
Mary-Kate Olsen原创
2025-01-18 20:12:12271浏览

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

使用.NET/C#检测CPU内核数

随着多处理的日益普及,确定CPU内核数以获得最佳性能至关重要。在.NET/C#中,可以通过多种方法访问此信息:

物理处理器

可以使用以下代码检索物理处理器的数量:

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

逻辑处理器

逻辑处理器(通常称为超线程)的数量可以使用以下任一代码获得:

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

排除的处理器

在某些Windows配置中,可能会排除特定处理器进行检测。为此,您可以使用setupapi.dll中找到的Windows API调用:

<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>

以上是如何确定 .NET/C# 中物理、逻辑和可用 CPU 核心的数量?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn