优先使用std::thread::hardware_concurrency()获取CPU核心数,跨平台且简洁;若返回0则回退到系统API:Windows调用GetSystemInfo,Linux读取/proc/cpuinfo统计processor字段。

在C++中跨平台获取CPU核心数,可以通过调用系统提供的API或标准库函数来实现。Windows和Linux有不同的接口,但我们可以封装成统一的接口,方便在不同系统上调用。
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <thread>
int main() {
    unsigned int num_cores = std::thread::hardware_concurrency();
    if (num_cores == 0) {
        std::cout << "无法获取核心数\n";
    } else {
        std::cout << "逻辑核心数: " << num_cores << '\n';
    }
    return 0;
}
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#ifdef _WIN32
#include <windows.h>
int get_cpu_cores_windows() {
    SYSTEM_INFO sysinfo;
    GetSystemInfo(&sysinfo);
    return sysinfo.dwNumberOfProcessors;
}
#endif
int main() {
#ifdef _WIN32
    std::cout << "Windows CPU核心数: " << get_cpu_cores_windows() << '\n';
#endif
    return 0;
}
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <fstream>
#include <string>
#ifdef __linux__
int get_cpu_cores_linux() {
    std::ifstream file("/proc/cpuinfo");
    std::string line;
    int count = 0;
    if (file.is_open()) {
        while (getline(file, line)) {
            if (line.rfind("processor", 0) == 0) {
                count++;
            }
        }
        file.close();
    }
    return count;
}
#endif
int main() {
#ifdef __linux__
    std::cout << "Linux CPU核心数: " << get_cpu_cores_linux() << '\n';
#endif
    return 0;
}
统一接口示例:
#include <iostream>
#include <thread>
int get_cpu_cores() {
    // 尝试使用标准库
    unsigned int hw_cores = std::thread::hardware_concurrency();
    if (hw_cores != 0) {
        return hw_cores;
    }
#ifdef _WIN32
    SYSTEM_INFO sysinfo;
    GetSystemInfo(&sysinfo);
    return sysinfo.dwNumberOfProcessors;
#elif __linux__
    std::ifstream file("/proc/cpuinfo");
    std::string line;
    int count = 0;
    while (getline(file, line)) {
        if (line.rfind("processor", 0) == 0) {
            count++;
        }
    }
    return count;
#else
    return 1; // 未知平台默认返回1
#endif
}
int main() {
    std::cout << "检测到CPU核心数: " << get_cpu_cores() << '\n';
    return 0;
}
基本上就这些。推荐优先使用 std::thread::hardware_concurrency(),简洁可靠。只有在需要更高精度或处理特殊场景时,才考虑调用系统API或解析系统文件。
以上就是c++++怎么在Windows和Linux上获取CPU核心数_c++跨平台获取CPU信息的方法的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号