Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 587
John Sheares Avatar asked Apr 04 '10 18:04

John Sheares


1 Answers

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;
    }
}
like image 186
Sam Harwell Avatar answered Sep 20 '22 01:09

Sam Harwell