有没有一种方法可以以平台无关的方式确定一台机器有多少个C/ c++内核?如果不存在这样的东西,如何确定每个平台(Windows/*nix/Mac)?


当前回答

关于OS X的更多信息:sysconf(_SC_NPROCESSORS_ONLN)仅在>= 10.5版本可用,而不是10.4版本。

另一种方法是HW_AVAILCPU/sysctl() BSD代码,在>= 10.2版本中可用。

其他回答

Note that "number of cores" might not be a particularly useful number, you might have to qualify it a bit more. How do you want to count multi-threaded CPUs such as Intel HT, IBM Power5 and Power6, and most famously, Sun's Niagara/UltraSparc T1 and T2? Or even more interesting, the MIPS 1004k with its two levels of hardware threading (supervisor AND user-level)... Not to mention what happens when you move into hypervisor-supported systems where the hardware might have tens of CPUs but your particular OS only sees a few.

最好的情况是告诉您在本地OS分区中拥有的逻辑处理单元的数量。除非您是管理程序,否则不要考虑看到真正的机器。今天这个规则唯一的例外是在x86领域,但非虚拟机的末日很快就会到来……

OS X替代方案:根据文档,前面描述的基于[[NSProcessInfo processInfo] processorCount]的解决方案仅在OS X 10.5.0上可用。对于较早版本的OS X,使用Carbon函数MPProcessors()。

如果你是一个Cocoa程序员,不要被这是Carbon这个事实吓到。你只需要将Carbon框架添加到你的Xcode项目中,MPProcessors()就可以使用了。

这个功能是c++ 11标准的一部分。

#include <thread>

unsigned int nthreads = std::thread::hardware_concurrency();

对于较老的编译器,可以使用Boost。线程库。

#include <boost/thread.hpp>

unsigned int nthreads = boost::thread::hardware_concurrency();

在任何一种情况下,hardware_concurrency()都会根据CPU内核和超线程单元的数量返回硬件能够并发执行的线程数。

您可能无法以独立于平台的方式获得它。Windows有处理器的数量。

Win32系统信息

还有一个Windows秘方:使用系统范围的环境变量NUMBER_OF_PROCESSORS:

printf("%d\n", atoi(getenv("NUMBER_OF_PROCESSORS")));