溫馨提示×

C++利用cpuid實現硬件特性檢測

c++
小樊
123
2024-09-12 19:05:32
欄目: 編程語言

在C++中,我們可以使用__cpuid__cpuidex內部函數來實現硬件特性檢測

#include <iostream>
#include <bitset>
#include <vector>
#include <string>
#include <intrin.h> // 包含CPUID相關的頭文件

// 定義一個結構體來存儲CPU信息
struct CPUInfo {
    int nIds;
    int nExIds;
    std::string vendor;
    std::string brand;
    bool isIntel;
    bool isAMD;
    std::bitset<32> f_1_ECX;
    std::bitset<32> f_1_EDX;
    std::bitset<32> f_7_EBX;
    std::bitset<32> f_7_ECX;
    std::bitset<32> f_81_ECX;
    std::bitset<32> f_81_EDX;
};

// 獲取CPU信息的函數
void getCPUInfo(CPUInfo& cpuinfo) {
    std::vector<std::array<int, 4>> data;
    std::array<int, 4> cpui;

    // 調用__cpuid獲取基本信息
    __cpuid(cpui.data(), 0);
    cpuinfo.nIds = cpui[0];

    for (int i = 0; i <= cpuinfo.nIds; ++i) {
        __cpuid(cpui.data(), i);
        data.push_back(cpui);
    }

    // 獲取CPU廠商信息
    char vendor[0x20];
    memset(vendor, 0, sizeof(vendor));
    *reinterpret_cast<int*>(vendor) = data[0][1];
    *reinterpret_cast<int*>(vendor + 4) = data[0][3];
    *reinterpret_cast<int*>(vendor + 8) = data[0][2];
    cpuinfo.vendor = vendor;
    cpuinfo.isIntel = (cpuinfo.vendor == "GenuineIntel");
    cpuinfo.isAMD = (cpuinfo.vendor == "AuthenticAMD");

    // 獲取擴展信息
    __cpuid(cpui.data(), 0x80000000);
    cpuinfo.nExIds = cpui[0];

    for (int i = 0x80000000; i <= cpuinfo.nExIds; ++i) {
        __cpuid(cpui.data(), i);
        data.push_back(cpui);
    }

    // 獲取CPU品牌信息
    char brand[0x40];
    memset(brand, 0, sizeof(brand));
    memcpy(brand, data[2].data(), sizeof(cpui));
    memcpy(brand + 16, data[3].data(), sizeof(cpui));
    memcpy(brand + 32, data[4].data(), sizeof(cpui));
    cpuinfo.brand = brand;

    // 獲取功能位信息
    cpuinfo.f_1_ECX = data[1][2];
    cpuinfo.f_1_EDX = data[1][3];
    cpuinfo.f_7_EBX = data[7][1];
    cpuinfo.f_7_ECX = data[7][2];
    cpuinfo.f_81_ECX = data[8][2];
    cpuinfo.f_81_EDX = data[8][3];
}

int main() {
    CPUInfo cpuinfo;
    getCPUInfo(cpuinfo);

    std::cout << "CPU Vendor: " << cpuinfo.vendor << std::endl;
    std::cout << "CPU Brand: " << cpuinfo.brand << std::endl;

    // 檢測SSE4.1支持
    if (cpuinfo.f_1_ECX[19]) {
        std::cout << "SSE4.1 supported" << std::endl;
    } else {
        std::cout << "SSE4.1 not supported" << std::endl;
    }

    // 檢測AVX支持
    if (cpuinfo.f_1_ECX[28]) {
        std::cout << "AVX supported" << std::endl;
    } else {
        std::cout << "AVX not supported" << std::endl;
    }

    return 0;
}

這個示例程序首先獲取CPU的基本信息,然后根據獲取到的信息判斷CPU是否支持特定的硬件特性。在這個例子中,我們檢查了SSE4.1和AVX的支持情況。你可以根據需要檢查其他硬件特性。

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