最常用方法是使用std::thread::hardware_concurrency()获取逻辑核心数,1.该标准库函数跨平台但可能返回0;2.Windows可用GetSystemInfo;3.Linux可用sysconf(_SC_NPROCESSORS_ONLN);4.建议封装统一接口优先使用标准库。

在C++中获取CPU核心数,最常用且跨平台的方法是使用标准库中的 std::thread::hardware_concurrency()。这个函数会返回系统支持的并发线程数量,通常等于逻辑核心数(包括超线程)。
#include <iostream>
#include <thread>
int main() {
unsigned int core_count = std::thread::hardware_concurrency();
if (core_count > 0) {
std::cout << "CPU核心数(逻辑核心): " << core_count << std::endl;
} else {
std::cout << "无法获取核心数" << std::endl;
}
return 0;
}
#include <iostream>
#include <windows.h>
int get_cpu_cores_windows() {
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
return sysinfo.dwNumberOfProcessors;
}
int main() {
std::cout << "CPU逻辑核心数: " << get_cpu_cores_windows() << std::endl;
return 0;
}
#include <iostream>
#include <unistd.h>
int main() {
long core_count = sysconf(_SC_NPROCESSORS_ONLN);
if (core_count != -1) {
std::cout << "CPU核心数: " << core_count << std::endl;
} else {
std::cout << "获取失败" << std::endl;
}
return 0;
}
#include <iostream>
unsigned int get_cpu_cores() {
#ifdef _WIN32
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
return sysinfo.dwNumberOfProcessors;
#elif defined(__linux__)
return sysconf(_SC_NPROCESSORS_ONLN);
#else
// 兜底使用标准库
return std::thread::hardware_concurrency();
#endif
}
基本上就这些方法。推荐优先使用 std::thread::hardware_concurrency(),它简洁、标准、可移植。若需更高精度或系统级信息,再考虑平台专用API。不复杂但容易忽略的是:返回值为0表示未知,记得做判断。
以上就是c++++怎么获取CPU核心数_c++ CPU核心数获取方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号