C/C++ 获取CPU核心数



  • 有时候我们的多线程程序要确定并发数(线程数), 这时候我们可能比较关心当前环境CPU核心数

    Windows

    Windows为我们提供了一些API, 比如GetSystemInfo(), 可以获得当前系统的一些信息, 这个函数包含在<windows.h>中, 然后获取其中的dwNumberOfProcessors成员即可

    #if defined(_WIN32)
    SYSTEM_INFO info;
    GetSystemInfo (&info);
    return info.dwNumberOfProcessors;
    

    Linux

    Linux则更加方便, 直接调用GNU函数get_nprocs()即可

    Code

    所以代码如下:

    int get_cpu_cores()
    {
    #if defined(_WIN32)
        SYSTEM_INFO info;
        GetSystemInfo (&info);
        return info.dwNumberOfProcessors;
    #elif defined(LINUX) || defined(SOLARIS) || defined(AIX)
        return get_nprocs();   //GNU fuction
    #else
    #error  UNKNOWN OS!
    #endif
    }
    


  • 标准库有函数用来查这个

    https://en.cppreference.com/w/cpp/thread/thread/hardware_concurrency

    #include <iostream>
    #include <thread>
     
    int main() {
        unsigned int n = std::thread::hardware_concurrency();
        std::cout << n << " concurrent threads are supported.\n";
    }
    

    查询失败会返回0,可以用上面的方法当fallback。


 

Copyright © 2018 bbs.dian.org.cn All rights reserved.

与 Dian 的连接断开,我们正在尝试重连,请耐心等待