Is there a way to reliably determine the total number of processor cores?

I need a reliable way to determine the number of processor cores on a computer. I am creating a numerical simulation C # application for modeling and I want to create the maximum number of working threads as kernels. I tried many of the suggested methods on the Internet, such as Environment.ProcessorCount, using WMI, this code: http://blogs.adamsoftware.net/Engine/DeterminingthenumberofphysicalCPUsonWindows.aspx None of them seem to think that AMD X2 has two cores . Any ideas?

Edit: Environment.ProcessorCount seems to be returning the correct number. This is on an Intel processor with a hyperthread that returns the wrong number. A hyperthread signature kernel returns 2 when it should be only 1.

+6
multithreading c # cpu-cores
source share
4 answers

See Processor Detection

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

+2
source share

From what I can tell, Environment.ProcessorCount can return the wrong value when working under WOW64 (like 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 problem, so I'm not sure why it was not resolved at this point.

Try this and see if the problem resolves:

 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; } } 
+6
source share

You get the right number of processors; AMD X2 is a true multi-core processor. The hypersurface kernel from Intel is treated by Windows as a processor with multiple cores. You can find out if hyperthreading is used with WMI, Win32_Processor , NumberOfCores vs NumberOfLogicalProcessors.

+2
source share

Have you checked the environment variable NUMBER_OF_PROCESSORS?

-one
source share

All Articles