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

前端 未结 13 1082
长发绾君心
长发绾君心 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:48

    The most accepted answer by bsruth on this page using __cpuid loops unnecessarily through not needed extended functions. If all you need to know is the Processor Brand String then there is no need to query 0x80000000.

    Wikipedia has a nice explanation with example code: https://en.wikipedia.org/wiki/CPUID#EAX=80000002h,80000003h,80000004h:_Processor_Brand_String

    #include   // GCC-provided
    #include 
    #include 
    
    int main(void) {
        uint32_t brand[12];
    
        if (!__get_cpuid_max(0x80000004, NULL)) {
            fprintf(stderr, "Feature not implemented.");
            return 2;
        }
    
        __get_cpuid(0x80000002, brand+0x0, brand+0x1, brand+0x2, brand+0x3);
        __get_cpuid(0x80000003, brand+0x4, brand+0x5, brand+0x6, brand+0x7);
        __get_cpuid(0x80000004, brand+0x8, brand+0x9, brand+0xa, brand+0xb);
        printf("Brand: %s\n", brand);
    }
    

    and here is the version i came up with to directly convert it to a std::string in c++

    std::string CPUBrandString;
    CPUBrandString.resize(49);
    uint *CPUInfo = reinterpret_cast(CPUBrandString.data());
    for (uint i=0; i<3; i++)
        __cpuid(0x80000002+i, CPUInfo[i*4+0], CPUInfo[i*4+1], CPUInfo[i*4+2], CPUInfo[i*4+3]);
    CPUBrandString.assign(CPUBrandString.data()); // correct null terminator
    std::cout << CPUBrandString << std::endl;
    

    this version is for linux, but it shouldn't be too hard to figure out for windows using __cpuid

提交回复
热议问题