编程找到一台机器上的内核数量 [英] Programmatically find the number of cores on a machine
本文介绍了编程找到一台机器上的内核数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法来确定一台机器从C / C多少个核心拥有++在平台无关的方式?如果没有这样的东西存在,那它确定每个平台(Windows / * nix中/苹果机)?
解决方案
C ++ 11
//可能会返回0时无法检测
无符号concurentThreadsSupported =的std ::螺纹:: hardware_concurrency();
参考:<一href=\"http://en.cp$p$pference.com/w/cpp/thread/thread/hardware_concurrency\">std::thread::hardware_concurrency
在C ++ C ++前11,没有可移植的方法。相反,你需要使用下列方法之一以上(通过适当的守卫 #IFDEF
行):
-
的Win32
SYSTEM_INFO SYSINFO;
的GetSystemInfo(安培; SYSINFO);
INT numCPU = sysinfo.dwNumberOfProcessors; -
Linux,Solaris和AIX和Mac OS X> = 10.4(即虎起)
INT numCPU =的sysconf(_SC_NPROCESSORS_ONLN);
-
FreeBSD的,MacOS X系统,NetBSD的,OpenBSD的,等等。
INT MIB [4];
INT numCPU;
的std ::为size_t的len = sizeof的(numCPU);/ *设置的MIB hw.ncpu * /
MIB [0] = CTL_HW;
MIB [1] = HW_AVAILCPU; //或者,尝试HW_NCPU;/ *从系统中获得的CPU的数量* /
的sysctl(MIB,2,&放大器; numCPU,&放大器; len个,NULL,0);如果(numCPU&。1)
{
MIB [1] = HW_NCPU;
的sysctl(MIB,2,&放大器; numCPU,&放大器; len个,NULL,0);
如果(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或iOS)
NSUInteger A = [[NSProcessInfo processInfo] processorCount]
NSUInteger B = [[NSProcessInfo processInfo] activeProcessorCount];
Is there a way to determine how many cores a machine has from C/C++ in a platform-independent way? If no such thing exists, what about determining it per-platform (Windows/*nix/Mac)?
解决方案
C++11
//may return 0 when not able to detect
unsigned concurentThreadsSupported = std::thread::hardware_concurrency();
Reference: std::thread::hardware_concurrency
In C++ prior to C++11, there's no portable way. Instead, you'll need to use one or more of the following methods (guarded by appropriate #ifdef
lines):
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];
这篇关于编程找到一台机器上的内核数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文