以编程方式查找计算机上的内核数(active processor cores bios)

有没有一种方法来确定一台机器有多少核心从 C / C ++ 在一个独立的平台的方式?

有没有一种方法来确定一台机器有多少核心从 C / C ++ 在一个独立的平台的方式?

817

C++ 11

#include <thread>
//may return 0 when not able to detect
const auto processor_count = std::thread::hardware_concurrency();

参考:std::thread::hardware_concurrency

在 C ++ 11 之前的 C ++ 中,没有可移植的方法。相反,您需要使用以下一种或多种方法(由适当的#ifdef行保护):

Win32

SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
int numCPU = sysinfo.dwNumberOfProcessors;

Linux 、 Solaris 、 AIX 和 Mac OS X & gt;= 10.4(即从 Tiger 开始)

int numCPU = sysconf(_SC_NPROCESSORS_ONLN);

FreeBSD 、 MacOS X 、 NetBSD 、 OpenBSD 等。

int mib[4];
int numCPU;
std::size_t len = sizeof(numCPU); 
/* set the mib for hw.ncpu */
mib[0] = CTL_HW;
mib[1] = HW_AILCPU;  // 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 & gt;= 10.5 或 iOS)

NSUInteger a = [[NSProcessInfo processInfo] processorCount];
NSUInteger b = [[NSProcessInfo processInfo] activeProcessorCount];
223

此功能是 C ++ 11 标准的一部分。

#include <thread>
unsigned int nthreads = std::thread::hardware_concurrency();

对于较旧的编译器,可以使用Boost.Thread库。

#include <boost/thread.hpp>
unsigned int nthreads = boost::thread::hardware_concurrency();

在任何一种情况下,hardware_concurrency()都会根据 CPU 内核和超线程单元的数量返回硬件能够并发执行的线程数。

65

OpenMP在许多平台(包括 Visual Studio 2005)上受支持,它提供了

int omp_get_num_procs();

函数,该函数返回调用时可用的处理器 / 内核数。

39

如果您具有汇编语言访问权限,则可以使用 CPUID 指令获取有关 CPU 的各种信息。它可以在操作系统之间移植,尽管您需要使用制造商特定的信息来确定如何查找内核数量。这里的a document that describes how to do it on Intel chipsthis one的第 11 页描述了 AMD 规范。

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(819)
Slack API并发送包含视频的消息
上一篇
purge-local-repository实际清除什么
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(56条)