2010-04-04 28 views
6

我需要一個可靠的方法來檢測核多少CPU是計算機上。我正在創建一個數值模擬的C#應用​​程序,並希望創建最大數量的正在運行的線程作爲核心。我已經嘗試了許多的周圍像Environment.ProcessorCount互聯網提出的方法,使用WMI,此代碼:http://blogs.adamsoftware.net/Engine/DeterminingthenumberofphysicalCPUsonWindows.aspx他們都不認爲一個AMD X2擁有兩個核心。有任何想法嗎?有沒有辦法可靠地檢測CPU內核的總數量?

編輯:看來Environment.ProcessorCount正在返回正確的號碼。它在超線程的intel CPU上返回錯誤的數字。具有超線程的signle核心返回2,當它應該只是1.

+0

您的鏈接不工作atm ... – ChristopheD 2010-04-04 18:46:38

+0

您在Taskmgr.exe,Performance選項卡中看到了多少個處理器? – 2010-04-04 19:00:37

+0

該鏈接有一天工作。 – 2010-04-04 19:06:04

回答

6

從我所知道的,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; 
    } 
} 
-1

你檢查NUMBER_OF_PROCESSORS環境變量?

+0

這在我的i7上顯示了8個,因此超線程核心在那裏計數 – 2016-10-18 12:26:56

2

你得到正確的處理器數量,AMD X2是真正的多核心處理器。英特爾超線程內核被Windows視爲多核CPU。你可以找出超線程是否被使用WMI,Win32_Processor,NumberOfCores VS NumberOfLogicalProcessors。

相關問題