How to determine the hardware (CPU and RAM) on a machine?

前端 未结 13 868
长发绾君心
长发绾君心 2020-12-31 03:29

I\'m working on a cross platform profiling suite, and would like to add information about the machine\'s CPU (architecture/clock speed/cores) and RAM(total) to the report of

13条回答
  •  一整个雨季
    2020-12-31 03:57

    I'm very late but here is my contribution. I tried to have a more modern C++ approach.

        #include  // NOTE this header is MSVC specific!
        #include 
        #include 
    
        std::string GetCpuInfo()
        {
            // 4 is essentially hardcoded due to the __cpuid function requirements.
            // NOTE: Results are limited to whatever the sizeof(int) * 4 is...
            std::array integerBuffer = {};
            constexpr size_t sizeofIntegerBuffer = sizeof(int) * integerBuffer.size();
    
            std::array charBuffer = {};
    
            // The information you wanna query __cpuid for.
            // https://docs.microsoft.com/en-us/cpp/intrinsics/cpuid-cpuidex?view=vs-2019
            constexpr std::array functionIds = {
                // Manufacturer
                //  EX: "Intel(R) Core(TM"
                0x8000'0002,
                // Model
                //  EX: ") i7-8700K CPU @"
                0x8000'0003,
                // Clockspeed
                //  EX: " 3.70GHz"
                0x8000'0004
            };
    
            std::string cpu;
    
            for (int id : functionIds)
            {
                // Get the data for the current ID.
                __cpuid(integerBuffer.data(), id);
                
                // Copy the raw data from the integer buffer into the character buffer
                std::memcpy(charBuffer.data(), integerBuffer.data(), sizeofIntegerBuffer);
    
                // Copy that data into a std::string
                cpu += std::string(charBuffer.data());
            }
    
            return cpu;
        }
    

    Here was the result of this function for myself: "Intel(R) Core(TM) i7-8700K CPU @ 3.70GHz"

    Honestly it's really annoying something like this hasn't been standardized...

提交回复
热议问题