英特尔手册第2卷指定以下公式来计算缓存大小:
缓存大小(字节)
=(路数+1)*(分区+1)*(行大小+1)*(集合+1)
=(EBX [31:22] + 1)*(EBX [21:12] + 1)*(EBX [11:0] + 1)*(ECX + 1)
其中,使用eax
设置为0x04
的cpuid
查询Ways
、Partitions
、Line_Size
和Sets
。
提供头文件声明:
x86_cache_size.h
:
unsigned int get_cache_line_size(unsigned int cache_level);
实现如下所示:
get_cache_line_size:
push rbx
mov ecx, edi
mov eax, 0x04
cpuid
mov eax, ebx
and eax, 0x7ff
inc eax
shr ebx, 12
mov edx, ebx
and edx, 0x1ff
inc edx
mul edx
shr ebx, 10
mov edx, ebx
and edx, 0x1ff
inc edx
mul edx
inc ecx
mul ecx
pop rbx
ret
在我的电脑上,它的工作方式如下:
#include "x86_cache_size.h"
int main(void){
unsigned int L1_cache_size = get_cache_line_size(1);
unsigned int L2_cache_size = get_cache_line_size(2);
unsigned int L3_cache_size = get_cache_line_size(3);
printf("L1 size = %u, L2 size = %u, L3 size = %u\n", L1_cache_size, L2_cache_size, L3_cache_size);
}
lscpu
命令,它可以非常好地显示x86 CPU数据,包括缓存摘要。 - Brent Bradburn