有没有一种方法可以以平台无关的方式确定一台机器有多少个C/ c++内核?如果不存在这样的东西,如何确定每个平台(Windows/*nix/Mac)?
当前回答
在Linux上,可以读取/proc/cpuinfo文件并计算核数。
其他回答
在linux上,据我所知,最好的编程方式是使用
sysconf(_SC_NPROCESSORS_CONF)
or
sysconf(_SC_NPROCESSORS_ONLN)
这些不是标准的,但是在我的Linux手册页中。
如果具有汇编语言访问权限,则可以使用CPUID指令获取有关CPU的各种信息。它在操作系统之间是可移植的,尽管您需要使用特定于制造商的信息来确定如何找到内核的数量。这里有一个文档描述了如何在英特尔芯片上做到这一点,这个文档的第11页描述了AMD的规范。
#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的实现。
Windows (x64和Win32)和c++ 11
共享单个处理器核心的逻辑处理器组的数目。(使用GetLogicalProcessorInformationEx,参见GetLogicalProcessorInformation)
size_t NumberOfPhysicalCores() noexcept {
DWORD length = 0;
const BOOL result_first = GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &length);
assert(GetLastError() == ERROR_INSUFFICIENT_BUFFER);
std::unique_ptr< uint8_t[] > buffer(new uint8_t[length]);
const PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX info =
reinterpret_cast< PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX >(buffer.get());
const BOOL result_second = GetLogicalProcessorInformationEx(RelationProcessorCore, info, &length);
assert(result_second != FALSE);
size_t nb_physical_cores = 0;
size_t offset = 0;
do {
const PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX current_info =
reinterpret_cast< PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX >(buffer.get() + offset);
offset += current_info->Size;
++nb_physical_cores;
} while (offset < length);
return nb_physical_cores;
}
注意,NumberOfPhysicalCores的实现在我看来远非简单(例如:"使用GetLogicalProcessorInformation或GetLogicalProcessorInformationEx")。相反,如果阅读MSDN的文档(显式地为GetLogicalProcessorInformation提供,隐式地为GetLogicalProcessorInformationEx提供),就会发现这是相当微妙的。
逻辑处理器的数量。(使用GetSystemInfo)
size_t NumberOfSystemCores() noexcept {
SYSTEM_INFO system_info;
ZeroMemory(&system_info, sizeof(system_info));
GetSystemInfo(&system_info);
return static_cast< size_t >(system_info.dwNumberOfProcessors);
}
注意,这两种方法都可以很容易地转换为C/ c++ 98/ c++ 03。
在Linux上,使用_SC_NPROCESSORS_ONLN可能是不安全的,因为它不是POSIX标准的一部分,sysconf手册也有同样的说明。所以有可能_SC_NPROCESSORS_ONLN不存在:
These values also exist, but may not be standard.
[...]
- _SC_NPROCESSORS_CONF
The number of processors configured.
- _SC_NPROCESSORS_ONLN
The number of processors currently online (available).
一个简单的方法是读取/proc/stat或/proc/cpuinfo并计算它们:
#include<unistd.h>
#include<stdio.h>
int main(void)
{
char str[256];
int procCount = -1; // to offset for the first entry
FILE *fp;
if( (fp = fopen("/proc/stat", "r")) )
{
while(fgets(str, sizeof str, fp))
if( !memcmp(str, "cpu", 3) ) procCount++;
}
if ( procCount == -1)
{
printf("Unable to get proc count. Defaulting to 2");
procCount=2;
}
printf("Proc Count:%d\n", procCount);
return 0;
}
使用 /proc/cpuinfo:
#include<unistd.h>
#include<stdio.h>
int main(void)
{
char str[256];
int procCount = 0;
FILE *fp;
if( (fp = fopen("/proc/cpuinfo", "r")) )
{
while(fgets(str, sizeof str, fp))
if( !memcmp(str, "processor", 9) ) procCount++;
}
if ( !procCount )
{
printf("Unable to get proc count. Defaulting to 2");
procCount=2;
}
printf("Proc Count:%d\n", procCount);
return 0;
}
同样的方法在shell中使用grep:
grep -c ^processor /proc/cpuinfo
Or
grep -c ^cpu /proc/stat # subtract 1 from the result
推荐文章
- 为什么这个结合赋值和相等检查的if语句返回true?
- cplusplus.com给出的错误、误解或坏建议是什么?
- C多行宏:do/while(0) vs作用域块
- 找出质数最快的算法是什么?
- 跨线程操作无效:控件“textBox1”从创建它的线程以外的线程访问
- time_t最终的类型定义是什么?
- 我需要显式处理负数或零时,总和平方数字?
- c++枚举类可以有方法吗?
- 函数名周围的括号是什么意思?
- 用C语言创建自己的头文件
- 格式化IO函数(*printf / *scanf)中的转换说明符%i和%d之间的区别是什么?
- 线和纤维的区别是什么?
- 将析构函数设为私有有什么用?
- main()中的Return语句vs exit()
- 为什么c#不提供c++风格的'friend'关键字?