我需要一种可靠的方法来检测计算机上有多少个CPU内核。我正在创建一个数值激烈的仿真C#应用程序,并希望创建最大数量的运行线程作为内核。我尝试了互联网上建议的许多方法,例如环境。 http://blogs.adamsoftware.net/engine/determiningthenumberofphysicalcpusonwindows.aspx 他们似乎都没有认为AMD X2有两个核心。有任何想法吗?

编辑:看来Environment.ProcessorCount正在返回正确的数字。它在具有超线程的Intel CPU上,它返回错误的数字。当它仅应为1时,带有超线程的签名核心将返回2。

有帮助吗?

解决方案

检测处理器的数量

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

其他提示

我能告诉 Environment.ProcessorCount 在WOW64下运行时可能会返回不正确的值(作为64位OS上的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;
    }
}

您正在获得正确的处理器计数,AMD X2是一个真正的多核处理器。 Windows将英特尔超线芯视为Muti Core CPU。您可以找出是否与WMI一起使用超线程, win32_processor, ,numberOfcores vs NumberFlogicalProcessors。

您是否检查了number_of_processors环境变量?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top