有没有办法以独立于平台的方式从 C/C++ 中确定一台机器有多少个内核?如果不存在这样的东西,那么如何确定每个平台(Windows/*nix/Mac)呢?
#include <thread> //may return 0 when not able to detect const auto processor_count = std::thread::hardware_concurrency();
参考:std::thread::hardware_concurrency
在 C11 之前的 C 中,没有可移植的方式。相反,您需要使用以下一种或多种方法(由适当的#ifdef行保护):
#ifdef
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo); int numCPU = sysinfo.dwNumberOfProcessors;
int numCPU = sysconf(_SC_NPROCESSORS_ONLN);
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; }
int numCPU = mpctl(MPC_GETNUMSPUS, NULL, NULL);
int numCPU = sysconf(_SC_NPROC_ONLN);
NSUInteger a = [[NSProcessInfo processInfo] processorCount];
NSUInteger b = [[NSProcessInfo processInfo] activeProcessorCount];