7

I need a reliable way to detect how many CPU cores are on a computer. I am creating a numerically intense simulation C# application and want to create the maximum number of running threads as cores. I have tried many of the methods suggested around the internet like Environment.ProcessorCount, using WMI, this code: http://blogs.adamsoftware.net/Engine/DeterminingthenumberofphysicalCPUsonWindows.aspx None of them seem to think a AMD X2 has two cores. Any ideas?

Edit: it appears that Environment.ProcessorCount is returning the correct number. It's on a intel CPU with hyperthreading that is returning the wrong number. A signle core with hyperthreading is returning 2, when it should only be 1.

4

4 回答 4

8

据我所知,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;
    }
}
于 2010-04-04T18:44:05.717 回答
2

请参见检测处理器数量

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

于 2010-04-04T19:21:09.183 回答
2

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

于 2010-04-04T19:27:19.007 回答
-1

您检查过 NUMBER_OF_PROCESSORS 环境变量吗?

于 2010-04-04T19:23:19.327 回答