Programmatically find the number of cores on a machine

前端 未结 19 2141
刺人心
刺人心 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:29

    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):

    • Win32

      SYSTEM_INFO sysinfo;
      GetSystemInfo(&sysinfo);
      int numCPU = sysinfo.dwNumberOfProcessors;
      
    • Linux, Solaris, AIX and Mac OS X >=10.4 (i.e. Tiger onwards)

      int numCPU = sysconf(_SC_NPROCESSORS_ONLN);
      
    • FreeBSD, MacOS X, NetBSD, OpenBSD, etc.

      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 or iOS)

      NSUInteger a = [[NSProcessInfo processInfo] processorCount];
      NSUInteger b = [[NSProcessInfo processInfo] activeProcessorCount];
      
    0 讨论(0)
  • 2020-11-22 17:29

    For Win32:

    While GetSystemInfo() gets you the number of logical processors, use GetLogicalProcessorInformationEx() to get the number of physical processors.

    0 讨论(0)
  • 2020-11-22 17:30

    OpenMP is supported on many platforms (including Visual Studio 2005) and it offers a

    int omp_get_num_procs();
    

    function that returns the number of processors/cores available at the time of call.

    0 讨论(0)
  • 2020-11-22 17:30

    Windows (x64 and Win32) and C++11

    The number of groups of logical processors sharing a single processor core. (Using GetLogicalProcessorInformationEx, see GetLogicalProcessorInformation as well)

    size_t NumberOfPhysicalCores() noexcept {
    
        DWORD length = 0;
        const BOOL result_first = GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &length);
        assert(GetLastError() == ERROR_INSUFFICIENT_BUFFER);
    
        std::unique_ptr< uint8_t[] > buffer(new uint8_t[length]);
        const PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX info = 
                reinterpret_cast< PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX >(buffer.get());
    
        const BOOL result_second = GetLogicalProcessorInformationEx(RelationProcessorCore, info, &length);
        assert(result_second != FALSE);
    
        size_t nb_physical_cores = 0;
        size_t offset = 0;
        do {
            const PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX current_info =
                reinterpret_cast< PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX >(buffer.get() + offset);
            offset += current_info->Size;
            ++nb_physical_cores;
        } while (offset < length);
            
        return nb_physical_cores;
    }
    

    Note that the implementation of NumberOfPhysicalCores is IMHO far from trivial (i.e. "use GetLogicalProcessorInformation or GetLogicalProcessorInformationEx"). Instead it is rather subtle if one reads the documentation (explicitly present for GetLogicalProcessorInformation and implicitly present for GetLogicalProcessorInformationEx) at MSDN.

    The number of logical processors. (Using GetSystemInfo)

    size_t NumberOfSystemCores() noexcept {
        SYSTEM_INFO system_info;
        ZeroMemory(&system_info, sizeof(system_info));
        
        GetSystemInfo(&system_info);
        
        return static_cast< size_t >(system_info.dwNumberOfProcessors);
    }
    

    Note that both methods can easily be converted to C/C++98/C++03.

    0 讨论(0)
  • 2020-11-22 17:31

    (Almost) Platform Independent function in c-code

    #ifdef _WIN32
    #include <windows.h>
    #elif MACOS
    #include <sys/param.h>
    #include <sys/sysctl.h>
    #else
    #include <unistd.h>
    #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
    }
    
    0 讨论(0)
  • 2020-11-22 17:33

    If you have assembly-language access, you can use the CPUID instruction to get all sorts of information about the CPU. It's portable between operating systems, though you'll need to use manufacturer-specific information to determine how to find the number of cores. Here's a document that describes how to do it on Intel chips, and page 11 of this one describes the AMD specification.

    0 讨论(0)
提交回复
热议问题