阅读量:108
cpuid 是一个 x86 和 x86-64 指令集中的指令,用于获取 CPU 的信息
- 获取 CPU 供应商:
#include
#include
#include
#include
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 class="hljs-keyword">return 0;
}
- 检测 CPU 支持的特性:
#include
#include
#include
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 class="hljs-keyword">else {
std::cout << "CPU does not support SSE4.1"<< std class="hljs-keyword">return 0;
}
- 获取 CPU 的基本信息:
#include
#include
#include
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 edx(abcd[3]) ;
std::bitset ecx(abcd[2]) ;
std::cout << "CPU features: "<< std class="hljs-string">"SSE: " << edx class="hljs-number">25]<< std class="hljs-string">"SSE2: " << edx class="hljs-number">26]<< std class="hljs-string">"SSE3: " << ecx class="hljs-number">0]<< std class="hljs-string">"SSSE3: " << ecx class="hljs-number">9]<< std class="hljs-string">"SSE4.1: " << ecx class="hljs-number">19]<< std class="hljs-string">"SSE4.2: " << ecx class="hljs-number">20]<< std class="hljs-function">int main() {
get_cpu_info();
return 0;
}
这些示例展示了如何使用 cpuid 指令在 C++ 中获取 CPU 的供应商、检测 CPU 支持的特性以及获取 CPU 的基本信息。请注意,这些示例仅适用于 x86 和 x86-64 架构的处理器。在其他架构上,需要使用相应的指令或库函数来获取类似的信息。