Home  >  Article  >  Backend Development  >  How to Access CPU Information in Linux Using the `cpuid` Instruction?

How to Access CPU Information in Linux Using the `cpuid` Instruction?

Linda Hamilton
Linda HamiltonOriginal
2024-10-31 11:56:02903browse

How to Access CPU Information in Linux Using the `cpuid` Instruction?

Accessing CPU Information on Linux Using the cpuid Instruction

In this question, a developer seeks to access CPU information in a Linux environment using a method akin to the _cpuinfo() function in the Windows API. The provided code attempts to utilize assembly instructions (cpuid) to retrieve this information, but the developer wishes to avoid the need for manual assembly.

The solution lies in utilizing the cpuid.h header file available when compiling code with GCC. This header declares two functions:

<code class="c">unsigned int __get_cpuid_max(unsigned int __ext, unsigned int *__sig);
int __get_cpuid(unsigned int __level, unsigned int *__eax, unsigned int *__ebx, unsigned int *__ecx, unsigned int *__edx);</code>

The __get_cpuid_max function returns the highest supported input value for the cpuid instruction. You can specify __ext as either 0x0 for basic information or 0x8000000 for extended information.

The __get_cpuid function retrieves CPU information for a specified level and returns the data in the eax, ebx, ecx, and edx registers. It returns a non-zero value if successful and zero if the requested level is not supported.

Usage Example:

<code class="c">#include <stdio.h>
#include <cpuid.h>

int main() {
  unsigned int eax, ebx, ecx, edx;

  // Get maximum supported CPUID level
  unsigned int max_level = __get_cpuid_max(0x0, NULL);

  // Iterate over different CPUID levels
  for (unsigned int level = 0; level <= max_level; level++) {
    // Retrieve CPUID data for the current level
    __get_cpuid(level, &eax, &ebx, &ecx, &edx);

    printf("Level %u: EAX=%u, EBX=%u, ECX=%u, EDX=%u\n", level, eax, ebx, ecx, edx);
  }

  return 0;
}</code>

The above is the detailed content of How to Access CPU Information in Linux Using the `cpuid` Instruction?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn