Programmatically find the number of cores on a machine

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

提交回复
热议问题