c++cmultithreadingmultiplatform

Programmatically find the number of cores on a machine


Is there a way to determine how many cores a machine has from C/C++ in a platform-independent way? If no such thing exists, what about determining it per-platform (Windows/*nix/Mac)?


Solution

  • C++11

    #include <thread>
    
    //may return 0 when not able to detect
    const auto processor_count = std::thread::hardware_concurrency();
    

    Reference: std::thread::hardware_concurrency


    In C++ prior to C++11, there's no portable way. Instead, you'll need to use one or more of the following methods (guarded by appropriate #ifdef lines):