Home > Backend Development > C++ > body text

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

Linda Hamilton
Release: 2024-10-31 11:56:02
Original
902 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!