Good day to all, tell me how in C / C ++ programmatically determine the number of cores in the processor? Maybe there is a method?

#include <iostream> using namespace std; int main() { int numCPU = sysconf(_SC_NPROCESSORS_ONLN); cout << numCPU << endl; } 

    2 answers 2

    Edited: Once found, then made a translation of a similar issue on StackOverflow .

    • Linux, Solaris, AIX, OS X> = 10.4:

       sysconf(_SC_NPROCESSORS_ONLN); 

      Or read in /proc/cpuinfo (for LSB-compatible distributions).

    • FreeBSD, OS X / Darwin, NetBSD, OpenBSD and their * BSD relatives:

       int mib[4] = {CTL_HW, HW_AVAILCPU, 0, 0}; size_t len = sizeof(numCPU); sysctl(mib, 2, &numCPU, &len, NULL, 0); if (numCPU < 0) { mib[1] = HW_NCPU; sysctl(mib, 2, &numCPU, &len, NULL, 0); } 
    • HPUX:

       mpctl(MPC_GETNUMSPUS, NULL, NULL) 
    • IRIX:

       sysconf(_SC_NPROC_ONLN) 
    • OS X> = 10.5 (on Objective-C):

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

       SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); numCPU = sysinfo.dwNumberOfProcessors; 
    • Thank you, I threw it into the cap, mb to whom it will come in handy. - Re1aps

    There is a cross-platform solution in boost and in the new standard:

     {boost,std}::thread::hardware_concurrency() 

    True, they are allowed to return 0 if for some reason the library cannot (or does not want) determine the number of cores, and gcc4.6 for Linux does that (apparently simply not implemented). But at the same time, the boost version yields the correct number. Now I tried under Mac Os X, gcc4.7 - everything correctly shows both the boost and std version.