gpt4 book ai didi

c++ - 如何在 Linux 中调用 "cpuid"?

转载 作者:可可西里 更新时间:2023-11-01 18:40:16 25 4
gpt4 key购买 nike

在为 Windows 编写新代码时,我偶然发现了来自 Windows API 的 _cpuinfo()。因为我主要处理 Linux 环境 (GCC),所以我想访问 CPUInfo。

我尝试了以下方法:

#include <iostream>

int main()
{
int a, b;

for (a = 0; a < 5; a++)
{
__asm ( "mov %1, %%eax; " // a into eax
"cpuid;"
"mov %%eax, %0;" // eax into b
:"=r"(b) // output
:"r"(a) // input
:"%eax","%ebx","%ecx","%edx" // clobbered register
);
std::cout << "The CPUID level " << a << " gives EAX= " << b << '\n';
}

return 0;
}

这使用了程序集,但我不想重新发明轮子。有没有其他不用汇编实现 CPUInfo 的方法?

最佳答案

由于您使用 GCC 进行编译,因此您可以包含声明以下函数的 cpuid.h:

/* Return highest supported input value for cpuid instruction.  ext can
be either 0x0 or 0x8000000 to return highest supported value for
basic or extended cpuid information. Function returns 0 if cpuid
is not supported or whatever cpuid returns in eax register. If sig
pointer is non-null, then first four bytes of the signature
(as found in ebx register) are returned in location pointed by sig. */
unsigned int __get_cpuid_max (unsigned int __ext, unsigned int *__sig)

/* Return cpuid data for requested cpuid level, as found in returned
eax, ebx, ecx and edx registers. The function checks if cpuid is
supported and returns 1 for valid cpuid information or 0 for
unsupported cpuid level. All pointers are required to be non-null. */
int __get_cpuid (unsigned int __level,
unsigned int *__eax, unsigned int *__ebx,
unsigned int *__ecx, unsigned int *__edx)

您不需要也不应该重新实现此功能。

关于c++ - 如何在 Linux 中调用 "cpuid"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14266772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com