有没有一种方法可以以平台无关的方式确定一台机器有多少个C/ c++内核?如果不存在这样的东西,如何确定每个平台(Windows/*nix/Mac)?
当前回答
C++11
#include <thread>
//may return 0 when not able to detect
const auto processor_count = std::thread::hardware_concurrency();
参考:std::线程::hardware_concurrency
在c++ 11之前的c++中,没有可移植的方法。相反,你需要使用以下一个或多个方法(由适当的#ifdef行保护):
Win32 SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); int numCPU = sysinfo.dwNumberOfProcessors; Linux, Solaris, AIX and Mac OS X >=10.4 (i.e. Tiger onwards) int numCPU = sysconf(_SC_NPROCESSORS_ONLN); FreeBSD, MacOS X, NetBSD, OpenBSD, etc. int mib[4]; int numCPU; std::size_t len = sizeof(numCPU); /* set the mib for hw.ncpu */ mib[0] = CTL_HW; mib[1] = HW_AVAILCPU; // alternatively, try HW_NCPU; /* get the number of CPUs from the system */ sysctl(mib, 2, &numCPU, &len, NULL, 0); if (numCPU < 1) { mib[1] = HW_NCPU; sysctl(mib, 2, &numCPU, &len, NULL, 0); if (numCPU < 1) numCPU = 1; } HPUX int numCPU = mpctl(MPC_GETNUMSPUS, NULL, NULL); IRIX int numCPU = sysconf(_SC_NPROC_ONLN); Objective-C (Mac OS X >=10.5 or iOS) NSUInteger a = [[NSProcessInfo processInfo] processorCount]; NSUInteger b = [[NSProcessInfo processInfo] activeProcessorCount];
其他回答
在Linux上,可以读取/proc/cpuinfo文件并计算核数。
您可能无法以独立于平台的方式获得它。Windows有处理器的数量。
Win32系统信息
OpenMP在许多平台(包括Visual Studio 2005)上都得到了支持,并且它提供了一种支持
int omp_get_num_procs();
函数返回调用时可用的处理器/核数。
Windows Server 2003及以后版本允许您利用GetLogicalProcessorInformation函数
http://msdn.microsoft.com/en-us/library/ms683194.aspx
还有一个Windows秘方:使用系统范围的环境变量NUMBER_OF_PROCESSORS:
printf("%d\n", atoi(getenv("NUMBER_OF_PROCESSORS")));