用于获取 C++ 中总核心数量的跨平台代码片段是什么?
可能的重复:
以编程方式检测物理处理器/核心的数量,或者如果超线程在 Windows、Mac 和 Linux 上处于活动状态
我想知道是否有任何跨平台(基于 std 或 boost 甚至 c)方法以跨平台方式获取内核总数? (适用于 Linux、Mac OS X 和 Windows)
Possible Duplicate:
Programatically detect number of physical processors/cores or if hyper-threading is active on Windows, Mac and Linux
I wonder if there is any crossplatform (std or boost based or even c) way to get totall number of cores in a crossplatform manner? (for linux Mac Os X and Windows)
您可以使用 OpenMP 的
omp_get_max_threads ()
函数。对于 g++,使用 -fopenmp 指令启用 OpenMP。对于 MS Visual Studio,请在项目属性 - 配置属性 - C/C++ - 语言中启用它。请注意,如果使用omp_set_num_threads ()
来限制 OpenMP 并行区域的线程数,则omp_get_max_threads ()
返回的硬件核心/线程数可能会少于实际数量。允许使用(不是程序启动时的问题)。您还应该注意,对于超线程 CPU,omp_get_max_threads ()
不会返回硬件 CPU 核心的数量,而是返回 CPU 支持的硬件线程的数量(并且超线程提供的附加线程不会返回)相当削减它)。You could use OpenMP's
omp_get_max_threads ()
function. For g++, enable OpenMP with the -fopenmp directive. For MS Visual Studio enable it in project properties - configuration properties - C/C++ - language. Be aware thatomp_get_max_threads ()
may return less than the actual number of hardware cores/threads ifomp_set_num_threads ()
has been used to limit the number of threads an OpenMP parallel region is allowed to use (not an issue at program start). You should also be aware that for hyper threading CPUsomp_get_max_threads ()
doesn't return the number of hardware CPU cores, but of hardware threads the CPU supports (and the additional threads provided by hyper threading don't quite cut it).