Programmatically find the number of cores on a machine

前端 未结 19 2142
刺人心
刺人心 2020-11-22 16:38

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/*

19条回答
  •  清酒与你
    2020-11-22 17:31

    (Almost) Platform Independent function in c-code

    #ifdef _WIN32
    #include 
    #elif MACOS
    #include 
    #include 
    #else
    #include 
    #endif
    
    int getNumCores() {
    #ifdef WIN32
        SYSTEM_INFO sysinfo;
        GetSystemInfo(&sysinfo);
        return sysinfo.dwNumberOfProcessors;
    #elif MACOS
        int nm[2];
        size_t len = 4;
        uint32_t count;
    
        nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;
        sysctl(nm, 2, &count, &len, NULL, 0);
    
        if(count < 1) {
            nm[1] = HW_NCPU;
            sysctl(nm, 2, &count, &len, NULL, 0);
            if(count < 1) { count = 1; }
        }
        return count;
    #else
        return sysconf(_SC_NPROCESSORS_ONLN);
    #endif
    }
    

提交回复
热议问题