【问题标题】:Is there a way to reliably detect the total number of CPU cores?有没有办法可靠地检测 CPU 内核的总数?
【发布时间】:2011-02-04 06:01:55
【问题描述】:

我需要一种可靠的方法来检测计算机上有多少 CPU 内核。我正在创建一个数值密集型模拟 C# 应用程序,并希望创建最大数量的运行线程作为核心。我已经尝试了许多互联网上建议的方法,例如 Environment.ProcessorCount,使用 WMI,此代码:http://blogs.adamsoftware.net/Engine/DeterminingthenumberofphysicalCPUsonWindows.aspx 他们似乎都不认为 AMD X2 有两个内核。有任何想法吗?

编辑:Environment.ProcessorCount 似乎返回了正确的数字。它在一个带有超线程的英特尔 CPU 上,它返回了错误的数字。具有超线程的信号核心返回 2,而它应该只有 1。

【问题讨论】:

  • 您的链接无法正常工作...
  • 您在 Taskmgr.exe 的“性能”选项卡中看到多少个处理器?
  • 该链接前几天还在工作。
  • 我可以在性能标签中看到两个。

标签: c# .net multithreading cpu-cores


【解决方案1】:

据我所知,Environment.ProcessorCount 在 WOW64(作为 64 位操作系统上的 32 位进程)下运行时可能会返回不正确的值,因为它所依赖的 P/Invoke 签名使用 GetSystemInfo 而不是GetNativeSystemInfo。这似乎是一个明显的问题,所以我不确定为什么到现在还没有解决。

试试这个,看看它是否能解决问题:

private static class NativeMethods
{
    [StructLayout(LayoutKind.Sequential)]
    internal struct SYSTEM_INFO
    {
        public ushort wProcessorArchitecture;
        public ushort wReserved;
        public uint dwPageSize;
        public IntPtr lpMinimumApplicationAddress;
        public IntPtr lpMaximumApplicationAddress;
        public UIntPtr dwActiveProcessorMask;
        public uint dwNumberOfProcessors;
        public uint dwProcessorType;
        public uint dwAllocationGranularity;
        public ushort wProcessorLevel;
        public ushort wProcessorRevision;
    }

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    internal static extern void GetNativeSystemInfo(ref SYSTEM_INFO lpSystemInfo);
}

public static int ProcessorCount
{
    get
    {
        NativeMethods.SYSTEM_INFO lpSystemInfo = new NativeMethods.SYSTEM_INFO();
        NativeMethods.GetNativeSystemInfo(ref lpSystemInfo);
        return (int)lpSystemInfo.dwNumberOfProcessors;
    }
}

【讨论】:

    【解决方案2】:

    Detecting the number of processors

    或者,使用GetLogicalProcessorInformation() Win32 API:http://msdn.microsoft.com/en-us/library/ms683194(VS.85).aspx

    【讨论】:

    • 第一个链接包含我需要的所有信息。谢谢!
    【解决方案3】:

    您得到了正确的处理器数量,AMD X2 是真正的多核处理器。 Windows 将 Intel 超线程内核视为多核 CPU。您可以了解 WMI、Win32_Processor、NumberOfCores 与 NumberOfLogicalProcessors 是否使用超线程。

    【讨论】:

      【解决方案4】:

      您是否检查过 NUMBER_OF_PROCESSORS 环境变量?

      【讨论】:

      • 这在我的 i7 上显示了 8 个,因此超线程内核也算在内
      猜你喜欢
      • 2021-05-10
      • 2016-04-17
      • 1970-01-01
      • 2022-01-17
      • 2012-05-22
      • 1970-01-01
      • 2016-12-26
      • 2014-11-30
      • 1970-01-01
      相关资源
      最近更新 更多