cpuid
是一個 x86 和 x86-64 指令集中的指令,用于獲取 CPU 的信息
#include<iostream>
#include<string>
#include <bitset>
#include <cstdint>
void cpuid(uint32_t eax, uint32_t ecx, uint32_t* abcd) {
asm volatile("cpuid" : "=a"(abcd[0]), "=b"(abcd[1]), "=c"(abcd[2]), "=d"(abcd[3]) : "a"(eax), "c"(ecx));
}
std::string get_vendor_name() {
uint32_t abcd[4];
cpuid(0, 0, abcd);
return std::string(reinterpret_cast<char*>(&abcd[1]), 4) +
std::string(reinterpret_cast<char*>(&abcd[3]), 4) +
std::string(reinterpret_cast<char*>(&abcd[2]), 4);
}
int main() {
std::cout << "CPU Vendor: "<< get_vendor_name()<< std::endl;
return 0;
}
#include<iostream>
#include <bitset>
#include <cstdint>
void cpuid(uint32_t eax, uint32_t ecx, uint32_t* abcd) {
asm volatile("cpuid" : "=a"(abcd[0]), "=b"(abcd[1]), "=c"(abcd[2]), "=d"(abcd[3]) : "a"(eax), "c"(ecx));
}
bool has_sse41() {
uint32_t abcd[4];
cpuid(1, 0, abcd);
return (abcd[2] & (1 << 19)) != 0;
}
int main() {
if (has_sse41()) {
std::cout << "CPU supports SSE4.1"<< std::endl;
} else {
std::cout << "CPU does not support SSE4.1"<< std::endl;
}
return 0;
}
#include<iostream>
#include <bitset>
#include <cstdint>
void cpuid(uint32_t eax, uint32_t ecx, uint32_t* abcd) {
asm volatile("cpuid" : "=a"(abcd[0]), "=b"(abcd[1]), "=c"(abcd[2]), "=d"(abcd[3]) : "a"(eax), "c"(ecx));
}
void get_cpu_info() {
uint32_t abcd[4];
cpuid(1, 0, abcd);
std::bitset<32> edx(abcd[3]);
std::bitset<32> ecx(abcd[2]);
std::cout << "CPU features: "<< std::endl;
std::cout << "SSE: " << edx[25]<< std::endl;
std::cout << "SSE2: " << edx[26]<< std::endl;
std::cout << "SSE3: " << ecx[0]<< std::endl;
std::cout << "SSSE3: " << ecx[9]<< std::endl;
std::cout << "SSE4.1: " << ecx[19]<< std::endl;
std::cout << "SSE4.2: " << ecx[20]<< std::endl;
}
int main() {
get_cpu_info();
return 0;
}
這些示例展示了如何使用 cpuid
指令在 C++ 中獲取 CPU 的供應商、檢測 CPU 支持的特性以及獲取 CPU 的基本信息。請注意,這些示例僅適用于 x86 和 x86-64 架構的處理器。在其他架構上,需要使用相應的指令或庫函數來獲取類似的信息。