查cpu缓存物理拓扑和共享范围,须读取/sys/devices/system/cpu/cpu0/cache/下各index*目录的level、type及shared_cpu_list字段;lscpu仅显示每核标称容量,不反映真实共享关系。

怎么查 CPU 缓存的物理拓扑和共享范围
Linux 不提供“缓存映射方式”这种抽象描述,真正可查的是缓存单元的物理层级、类型、大小、共享 CPU 列表——这些才是决定 cache line 如何被多个逻辑核访问的关键依据。
别依赖 lscpu 输出的 L1d/L2 数字做跨核调度判断,它只告诉你每核标称容量,不反映硬件是否共享。真实行为取决于 /sys/devices/system/cpu/cpu0/cache/index* 下每个缓存单元的 shared_cpu_list 字段。
- 先确认 CPU 0 在线:
cat /sys/devices/system/cpu/online,避免读取离线 CPU 的陈旧数据 - 列出所有缓存索引:
ls /sys/devices/system/cpu/cpu0/cache/,通常有index0~index3 - 对每个
indexN,检查:
—cat /sys/devices/system/cpu/cpu0/cache/indexN/level(1=L1,2=L2,3=L3)
—cat /sys/devices/system/cpu/cpu0/cache/indexN/type(Data / Instruction / Unified)
—cat /sys/devices/system/cpu/cpu0/cache/indexN/shared_cpu_list(关键!输出0-3表示这组缓存被 CPU 0~3 共享)
为什么 shared_cpu_list 比 cache size 更重要
一个 L2 cache: 256K 的输出毫无意义,除非你知道它是 per-core 还是 cluster-shared。Intel Core i7-11800H 的 L2 是每核 512KB 私有;而 AMD Zen3 的 L2 是每核 512KB,但 L3 是 32MB 八核共享——shared_cpu_list 直接告诉你哪几个逻辑核会竞争同一组 cache set。
- 若
shared_cpu_list只含单个数字(如0),说明该缓存完全私有,无 false sharing 风险 - 若输出
0,2,4,6,说明这是由超线程配对或 core complex 内部共享的缓存,不是全 CPU 共享 - 若输出
0-15,且你有 16 核 CPU,则大概率是 L3,但需结合level和type确认 - 虚拟机里看到
shared_cpu_list是0-7,不代表宿主机物理拓扑如此——KVM 可能做了简化模拟
怎么算 cache line 大小和关联度
coherency_line_size 几乎总是 64,这才是影响内存对齐、prefetch 和 false sharing 的实际单位。它和 cache 容量无关,但决定了每次加载/失效操作的最小粒度。
- 查行大小:
cat /sys/devices/system/cpu/cpu0/cache/index0/coherency_line_size→ 通常返回64 - 查组数:
cat /sys/devices/system/cpu/cpu0/cache/index0/number_of_sets - 查路数:
cat /sys/devices/system/cpu/cpu0/cache/index0/ways_of_associativity - 验证一致性:
size = coherency_line_size × number_of_sets × ways_of_associativity,结果应等于cat /sys/devices/system/cpu/cpu0/cache/index0/size
例如:64 × 64 × 8 = 32768 = 32K → 对应典型 L1d 参数。这个计算关系比背诵“8-way set associative”有用得多。
哪些命令会误导你对缓存映射的理解
lscpu、/proc/cpuinfo、dmidecode -t processor 都只提供静态摘要,无法反映运行时拓扑变化(如 Intel 的 Cache Allocation Technology 或 AMD 的 Core Complex 启用状态)。
-
lscpu | grep "L2"显示L2 cache: 256K→ 你不知道这是 per-core 还是 per-cluster -
grep "cache size" /proc/cpuinfo输出多行cache size : 32 KB→ 它不标注对应哪一级,也不说明是否重复(不同核心可能输出相同值) -
sudo dmidecode -t processor中的L2 Cache Handle描述的是 BIOS 固件报告值,微码更新后可能未同步 - 所有这些命令都无法告诉你:CPU 0 和 CPU 1 是否共享同一组 L2 cache lines —— 只有
shared_cpu_list能
真正做 NUMA 绑核、cache-aware scheduling 或诊断 false sharing 时,必须下钻到 /sys/devices/system/cpu/cpu*/cache/index*/shared_cpu_list,其他都是参考信息。











