有没有一种方法可以以平台无关的方式确定一台机器有多少个C/ c++内核?如果不存在这样的东西,如何确定每个平台(Windows/*nix/Mac)?
当前回答
还有一个Windows秘方:使用系统范围的环境变量NUMBER_OF_PROCESSORS:
printf("%d\n", atoi(getenv("NUMBER_OF_PROCESSORS")));
其他回答
Hwloc (http://www.open-mpi.org/projects/hwloc/)值得一看。虽然需要将另一个库集成到代码中,但它可以提供关于处理器的所有信息(核数、拓扑结构等)。
Windows Server 2003及以后版本允许您利用GetLogicalProcessorInformation函数
http://msdn.microsoft.com/en-us/library/ms683194.aspx
#include <stdint.h>
#if defined(__APPLE__) || defined(__FreeBSD__)
#include <sys/sysctl.h>
uint32_t num_physical_cores(void)
{
uint32_t num_cores = 0;
size_t num_cores_len = sizeof(num_cores);
sysctlbyname("hw.physicalcpu", &num_cores, &num_cores_len, 0, 0);
return num_cores;
}
#elif defined(__linux__)
#include <unistd.h>
#include <stdio.h>
uint32_t num_physical_cores(void)
{
uint32_t lcores = 0, tsibs = 0;
char buff[32];
char path[64];
for (lcores = 0;;lcores++) {
FILE *cpu;
snprintf(path, sizeof(path), "/sys/devices/system/cpu/cpu%u/topology/thread_siblings_list", lcores);
cpu = fopen(path, "r");
if (!cpu) break;
while (fscanf(cpu, "%[0-9]", buff)) {
tsibs++;
if (fgetc(cpu) != ',') break;
}
fclose(cpu);
}
return lcores / (tsibs / lcores);
}
#else
#error Unrecognized operating system
#endif
这将返回系统上的物理核数。这与大多数答案提供的逻辑核数量不同。如果您希望确定一个不执行阻塞I/O且不休眠的线程池的大小,那么您希望使用物理内核的数量,而不是逻辑(超线程)内核的数量。
这个答案只提供Linux和bsd的实现。
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领域,但非虚拟机的末日很快就会到来……
您可能无法以独立于平台的方式获得它。Windows有处理器的数量。
Win32系统信息
推荐文章
- 有效,但毫无价值的语法在开关情况下?
- 如何为Fedora安装g++ ?
- Std::cin输入空格?
- c++标准是否要求iostreams的性能很差,或者我只是在处理一个糟糕的实现?
- 同步vs锁定
- 在ExecutorService的提交和执行之间进行选择
- 有一个好的Valgrind Windows的替代品吗?
- gcc在哪里查找C和c++头文件?
- 为什么我们需要require require ?
- CountDownLatch是如何在Java多线程中使用的?
- 如果我同步了同一个类上的两个方法,它们能同时运行吗?
- 解析c++中的命令行参数?
- 我如何在c++中创建一个随机的字母数字字符串?
- c++中的atan和atan2有什么区别?
- 现代c++能让你免费获得性能吗?