2

我想编写一个简单的程序来调用__get_cpuid以获取缓存信息:

#include <cpuid.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    int leaf = atoi(argv[1]);

    uint32_t eax = 0, ebx = 0, ecx = 0, edx = 0;

    if (__get_cpuid(leaf, &eax, &ebx, &ecx, &edx))
    {
        printf("leaf=%d, eax=0x%x, ebx=0x%x, ecx=0x%x, edx=0x%x\n",
                leaf, eax, ebx, ecx, edx);
    }
    return 0;
}

首先,我通过leaf2:

$ ./a.out 2
leaf=2, eax=0x76035a01, ebx=0xf0b2ff, ecx=0x0, edx=0xca0000

由于存在0xffin ebx,这意味着我可以从leaf=4(请参阅此处)获取缓存信息:

$ ./a.out 4
leaf=4, eax=0x0, ebx=0x0, ecx=0x0, edx=0x0

但这一次,所有返回值都是0. 为什么我无法从中获取有效信息__get_cpuid

4

1 回答 1

3

Looking at the linked reference for EAX=4 we see that ECX needs to be set to "cache level to query (e.g. 0=L1D, 1=L2, or 0=L1D, 1=L1I, 2=L2)".

I couldn't quickly find any documentation on __get_cpuid, but a search did turn up the soure code, where I noticed that you need to call __get_cpuid_count to have ecx set before the call to cpuid (otherwise you'll get random answers - mostly 0s it seems).

于 2017-09-18T06:54:05.270 回答