プログラムでマシンのコア数を見つける

C++11

#include <thread>

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

参照:std::thread::hardware_concurrency

C++11 より前の C++ では、移植可能な方法はありません。代わりに、次のメソッドの 1 つ以上を使用する必要があります (適切な #ifdef で保護されています)。 行):

    <リ>

    Win32

    SYSTEM_INFO sysinfo;
    GetSystemInfo(&sysinfo);
    int numCPU = sysinfo.dwNumberOfProcessors;
    
    <リ>

    Linux、Solaris、AIX、および Mac OS X>=10.4 (つまり、Tiger 以降)

    int numCPU = sysconf(_SC_NPROCESSORS_ONLN);
    
    <リ>

    FreeBSD、MacOS X、NetBSD、OpenBSD など

    int mib[4];
    int numCPU;
    std::size_t len = sizeof(numCPU); 
    
    /* set the mib for hw.ncpu */
    mib[0] = CTL_HW;
    mib[1] = HW_AVAILCPU;  // alternatively, try HW_NCPU;
    
    /* get the number of CPUs from the system */
    sysctl(mib, 2, &numCPU, &len, NULL, 0);
    
    if (numCPU < 1) 
    {
        mib[1] = HW_NCPU;
        sysctl(mib, 2, &numCPU, &len, NULL, 0);
        if (numCPU < 1)
            numCPU = 1;
    }
    
    <リ>

    HPUX

    int numCPU = mpctl(MPC_GETNUMSPUS, NULL, NULL);
    
    <リ>

    IRIX

    int numCPU = sysconf(_SC_NPROC_ONLN);
    
    <リ>

    Objective-C (Mac OS X>=10.5 または iOS)

    NSUInteger a = [[NSProcessInfo processInfo] processorCount];
    NSUInteger b = [[NSProcessInfo processInfo] activeProcessorCount];
    

この機能は C++11 標準の一部です。

#include <thread>

unsigned int nthreads = std::thread::hardware_concurrency();

古いコンパイラの場合は、Boost.Thread ライブラリを使用できます。

#include <boost/thread.hpp>

unsigned int nthreads = boost::thread::hardware_concurrency();

どちらの場合も、hardware_concurrency() CPU コアとハイパースレッディング ユニットの数に基づいて、ハードウェアが同時に実行できるスレッドの数を返します。


OpenMP は多くのプラットフォーム (Visual Studio 2005 を含む) でサポートされており、

int omp_get_num_procs();

呼び出し時に利用可能なプロセッサ/コアの数を返す関数。