温馨提示×

C++利用cpuid实现硬件特性检测

c++
小樊
81
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