溫馨提示×

如何在C++中使用cpuid獲取處理器信息

c++
小樊
315
2024-09-12 19:02:04
欄目: 編程語言

cpuid 是一個 x86/x64 指令,它可以用來獲取 CPU 的基本信息

#include <iostream>
#include <string>
#include <bitset>
#include <cstdint>

void cpuid(uint32_t eax, uint32_t ecx, uint32_t* abcd) {
    // 使用 GCC 和 Clang 的內建函數
    #if defined(__GNUC__) || defined(__clang__)
        __cpuid_count(eax, ecx, abcd[0], abcd[1], abcd[2], abcd[3]);
    // 使用 MSVC 的內建函數
    #elif defined(_MSC_VER)
        __cpuidex(reinterpret_cast<int*>(abcd), eax, ecx);
    #else
        #error "Unsupported compiler"
    #endif
}

std::string get_vendor_string() {
    uint32_t abcd[4];
    cpuid(0, 0, abcd);

    // 將結果轉換為字符串
    std::string vendor;
    vendor += std::string(reinterpret_cast<char*>(&abcd[1]), 4);
    vendor += std::string(reinterpret_cast<char*>(&abcd[3]), 4);
    vendor += std::string(reinterpret_cast<char*>(&abcd[2]), 4);
    return vendor;
}

int main() {
    std::cout << "CPU Vendor: " << get_vendor_string() << std::endl;
    return 0;
}

這個程序首先定義了一個 cpuid 函數,該函數使用編譯器特定的內建函數(例如 __cpuid_count)來執行 cpuid 指令。然后,我們定義了一個 get_vendor_string 函數,該函數調用 cpuid 函數并返回 CPU 供應商的字符串。最后,main 函數打印出 CPU 供應商的字符串。

請注意,這個示例僅適用于 x86/x64 架構的處理器。如果你需要在其他架構上運行此代碼,你可能需要使用不同的指令或庫函數來獲取 CPU 信息。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女