有没有一种方法可以以平台无关的方式确定一台机器有多少个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];

其他回答

如果具有汇编语言访问权限,则可以使用CPUID指令获取有关CPU的各种信息。它在操作系统之间是可移植的,尽管您需要使用特定于制造商的信息来确定如何找到内核的数量。这里有一个文档描述了如何在英特尔芯片上做到这一点,这个文档的第11页描述了AMD的规范。

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领域,但非虚拟机的末日很快就会到来……

与c++无关,但在Linux上我通常这样做:

grep processor /proc/cpuinfo | wc -l

适用于bash/perl/python/ruby等脚本语言。

Windows Server 2003及以后版本允许您利用GetLogicalProcessorInformation函数

http://msdn.microsoft.com/en-us/library/ms683194.aspx

你也可以在。net中使用WMI,但这样你就依赖于WMI服务的运行 等。有时它在本地工作,但当相同的代码在服务器上运行时就会失败。 我认为这是一个名称空间问题,与您正在读取其值的“名称”有关。