プログラムでマシン上のコア数を調べる 質問する

プログラムでマシン上のコア数を調べる 質問する

プラットフォームに依存しない方法で、C/C++ からマシンのコア数を判断する方法はありますか? そのような方法がない場合、プラットフォーム (Windows/*nix/Mac) ごとに判断するのはどうでしょうか?

ベストアンサー1

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行で保護されています)。

  • ウィン32

    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);
    
  • アイリックス

    int numCPU = sysconf(_SC_NPROC_ONLN);
    
  • Objective-C (Mac OS X >=10.5 または iOS)

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

おすすめ記事