有没有办法可靠地检测CPU核心总数?
我需要一种可靠的方法来检测计算机上有多少个 CPU 核心。我正在创建一个数值密集型模拟 C# 应用程序,并希望创建最大数量的运行线程作为核心。我已经尝试了许多互联网上建议的方法,例如Environment.ProcessorCount,使用WMI,这段代码: http ://blogs.adamsoftware.net/Engine/DeterminingthenumberofphysicalCPUsonWindows.aspx 他们似乎都不认为 AMD X2 有两个核心。有什么想法吗?
编辑:Environment.ProcessorCount 似乎返回了正确的数字。它位于具有超线程的英特尔 CPU 上,返回错误的数字。具有超线程的单核返回 2,而它应该只返回 1。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
据我所知,在 WOW64 下运行时(作为 64 位操作系统上的 32 位进程),
Environment.ProcessorCount
可能会返回不正确的值,因为它依赖的 P/Invoke 签名使用 < a href="http://msdn.microsoft.com/en-us/library/ms724381.aspx" rel="noreferrer">GetSystemInfo
而不是GetNativeSystemInfo
。这似乎是一个明显的问题,所以我不确定为什么此时它还没有得到解决。尝试此操作并查看是否可以解决问题:
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 usesGetSystemInfo
instead ofGetNativeSystemInfo
. 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:
请参阅检测处理器数量
或者,使用
GetLogicalProcessorInformation() Win32 API:http://msdn.microsoft. com/en-us/library/ms683194(VS.85).aspx
See Detecting the number of processors
Alternatively, use the
GetLogicalProcessorInformation()
Win32 API: http://msdn.microsoft.com/en-us/library/ms683194(VS.85).aspx您获得了正确的处理器数量,AMD X2 是真正的多核处理器。 Windows 将 Intel 超线程核心视为多核 CPU。您可以了解 WMI 是否使用超线程,Win32_Processor,NumberOfCores 与 NumberOfLogicalProcessors。
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.
您检查过 NUMBER_OF_PROCESSORS 环境变量吗?
Have you checked the NUMBER_OF_PROCESSORS environment variable ?