c++怎么获取CPU的核心数量_c++获取CPU核心数方法

答案是使用std::Thread::hardware_concurrency()可跨平台获取CPU核心数,返回硬件支持的线程并发数,若失败则返回0;windows可用GetSystemInfo获取dwNumberOfProcessors,linux/unix可用sysconf(_SC_NPROCESSORS_ONLN)获取在线核心数,推荐优先使用标准库函数。

c++怎么获取CPU的核心数量_c++获取CPU核心数方法

c++中获取CPU核心数量有多种方法,具体取决于操作系统和使用的标准库。最简单且跨平台的方式是使用C++11及以上标准提供的std::thread::hardware_concurrency()函数。

使用 std::thread::hardware_concurrency()

这是C++标准库中推荐的跨平台方式,用于查询系统支持的并发线程数量,通常等于CPU核心数(包括逻辑核心)。

  • 该函数定义在<thread>头文件中
  • 返回值为无符号整数,表示硬件支持的线程并发数
  • 若无法确定,可能返回0

示例代码:

 #include <iostream> #include <thread>  int main() {     unsigned int num_cores = std::thread::hardware_concurrency();     if (num_cores != 0) {         std::cout << "CPU核心数: " << num_cores << std::endl;     } else {         std::cout << "无法获取CPU核心数" << std::endl;     }     return 0; } 

windows平台:使用GetSystemInfo

在Windows系统中,可以通过调用Win32 API中的GetSystemInfo函数获取处理器信息。

立即学习C++免费学习笔记(深入)”;

c++怎么获取CPU的核心数量_c++获取CPU核心数方法

阿里云-虚拟数字人

阿里云-虚拟数字人是什么? …

c++怎么获取CPU的核心数量_c++获取CPU核心数方法2

查看详情 c++怎么获取CPU的核心数量_c++获取CPU核心数方法

  • 需要包含<windows.h>
  • 填充SYSTEM_INFO结构体后读取wProcessorCount

示例代码:

 #include <iostream> #include <windows.h>  int main() {     SYSTEM_INFO sysinfo;     GetSystemInfo(&sysinfo);     std::cout << "CPU核心数: " << sysinfo.dwNumberOfProcessors << std::endl;     return 0; } 

Linux/Unix平台:使用sysconf

在类Unix系统中,可通过sysconf函数配合_SC_NPROCESSORS_ONLN参数获取在线CPU核心数。

  • 需要包含<unistd.h>
  • 适用于Linux、macOS等系统

示例代码:

 #include <iostream> #include <unistd.h>  int main() {     long num_cores = sysconf(_SC_NPROCESSORS_ONLN);     std::cout << "CPU核心数: " << num_cores << std::endl;     return 0; } 

基本上就这些常用方法。优先推荐使用std::thread::hardware_concurrency(),因为它简洁、跨平台,适合大多数场景。如果需要更精确的控制或兼容旧环境,再考虑系统特定API。

上一篇
下一篇
text=ZqhQzanResources