Is there a way to reliably detect the total number of CPU cores?

后端 未结 4 1648
北海茫月
北海茫月 2021-01-18 05:57

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

相关标签:
4条回答
  • 2021-01-18 06:09

    From what I can tell, Environment.ProcessorCount may return an incorrect value when running under WOW64 (as a 32-bit process on a 64-bit OS) because the P/Invoke signature it relies on uses GetSystemInfo instead of GetNativeSystemInfo. This seems like an obvious issue, so I'm not sure why it wouldn't have been resolved by this point.

    Try this and see if it resolves the issue:

    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;
        }
    }
    
    0 讨论(0)
  • 2021-01-18 06:18

    Have you checked the NUMBER_OF_PROCESSORS environment variable ?

    0 讨论(0)
  • 2021-01-18 06:25

    See Detecting the number of processors

    Alternatively, use the GetLogicalProcessorInformation() Win32 API: http://msdn.microsoft.com/en-us/library/ms683194(VS.85).aspx

    0 讨论(0)
  • 2021-01-18 06:27

    You are getting the correct processor count, AMD X2 is a true multi-core processor. An Intel hyperthreaded core is treated by Windows as a muti-core CPU. You can find out whether or not hyperthreading is used with WMI, Win32_Processor, NumberOfCores vs NumberOfLogicalProcessors.

    0 讨论(0)
提交回复
热议问题