有没有一种方法可以以平台无关的方式确定一台机器有多少个C/ c++内核?如果不存在这样的东西,如何确定每个平台(Windows/*nix/Mac)?
当前回答
Hwloc (http://www.open-mpi.org/projects/hwloc/)值得一看。虽然需要将另一个库集成到代码中,但它可以提供关于处理器的所有信息(核数、拓扑结构等)。
其他回答
这个功能是c++ 11标准的一部分。
#include <thread>
unsigned int nthreads = std::thread::hardware_concurrency();
对于较老的编译器,可以使用Boost。线程库。
#include <boost/thread.hpp>
unsigned int nthreads = boost::thread::hardware_concurrency();
在任何一种情况下,hardware_concurrency()都会根据CPU内核和超线程单元的数量返回硬件能够并发执行的线程数。
在Linux上,可以读取/proc/cpuinfo文件并计算核数。
OpenMP在许多平台(包括Visual Studio 2005)上都得到了支持,并且它提供了一种支持
int omp_get_num_procs();
函数返回调用时可用的处理器/核数。
在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
Windows Server 2003及以后版本允许您利用GetLogicalProcessorInformation函数
http://msdn.microsoft.com/en-us/library/ms683194.aspx
推荐文章
- decltype(auto)的一些用途是什么?
- Shared_ptr转换为数组:应该使用它吗?
- 使用C返回一个数组
- Printf与std::字符串?
- 禁用复制构造函数
- 自动化invokerrequired代码模式
- 只接受特定类型的c++模板
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 为什么pthreads的条件变量函数需要互斥?
- c++ 11中的递归lambda函数
- 在c++中指针使用NULL或0(零)吗?
- 在c++中,如何将int值附加到字符串中?
- __FILE__宏显示完整路径