我希望使用x86汇编语言找到L1或L2缓存的CPU缓存大小。我听说cpuid和MSR寄存器具有系统特定的数据。可以有人告诉我如何获取缓存大小吗?
这是一个使用CPUID指令查找的最简示例:
#include <stdio.h>
#include <limits.h>
#define cpuid(id) __asm__( "cpuid" : "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx) : "a"(id), "b"(0), "c"(0), "d"(0))
#define b(val, base, end) ((val << (__WORDSIZE-end-1)) >> (__WORDSIZE-end+base-1))
int main(int argc, char **argv)
{
unsigned long eax, ebx, ecx, edx;
cpuid(0);
printf("identification: \"%.4s%.4s%.4s\"\n", (char *)&ebx, (char *)&edx, (char *)&ecx);
printf("cpu information:\n");
cpuid(1);
printf(" family %ld model %ld stepping %ld efamily %ld emodel %ld\n",
b(eax, 8, 11), b(eax, 4, 7), b(eax, 0, 3), b(eax, 20, 27), b(eax, 16, 19));
printf(" brand %ld cflush sz %ld*8 nproc %ld apicid %ld\n",
b(ebx, 0, 7), b(ebx, 8, 15), b(ebx, 16, 23), b(ebx, 24, 31));
cpuid(0x80000006);
printf("L1 cache size (per core): %ld KB\n", b(ecx, 16, 31));
return(0);
}
正如Soravux所建议的那样,您需要查看CPUID
指令。(您可能需要查看例如Intel 64和IA-32体系结构软件开发人员手册第2A卷这里中的CPUID
).
您可能最感兴趣的功能是:CPUID.EAX=02h
和/或CPUID.EAX=04h
(取决于您的确切需求)。这些函数提供了相当多的输出,因此我不会在此处详细介绍,但Intel和AMD的手册应该包含您所需的所有内容。