mcpField
C
cpu-cache-opt

cpu-cache-opt

github.com/mohitmishra786开发269666 次安装18 周前更新
代码仓库

关于 cpu-cache-opt

面向 Agent 的 CPU 缓存优化技能,帮助分析缓存未命中并改善数据布局和算法。内容涵盖 perf 测量、伪共享、预取及分块处理。

主要功能

  1. 01使用 perf 测量缓存事件
  2. 02AoS 与 SoA 数据布局
  3. 03检测并缓解伪共享
  4. 04手动预取提示
  5. 05缓存友好算法与循环分块

适用场景

  1. 01排查程序缓存未命中率偏高
  2. 02改善多线程计数器的伪共享
  3. 03优化矩阵运算的数据访问

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/mohitmishra786/low-level-dev-skills --skill cpu-cache-opt

安装后在 Claude Code 中输入/cpu-cache-opt确认已加载。

附带文件references/cache-counters.md

详细介绍

CPU 缓存优化

目的

指导 Agent 进行缓存感知编程:使用 perf 诊断缓存未命中、转换数据布局(AoS→SoA)、检测并修复伪共享、预取,以及设计缓存友好型算法。

触发条件

  • “我的程序缓存未命中率很高,该如何解决?”
  • “什么是伪共享?如何检测?”
  • “应该使用 AoS 还是 SoA 数据布局?”
  • “如何使用 perf 测量缓存性能?”
  • “如何使用 __builtin_prefetch?”
  • “我的多线程程序因为缓存问题,比单线程程序慢”

工作流

1. 测量缓存性能
# Basic cache counters
perf stat -e cache-references,cache-misses,cycles,instructions ./prog

# L1/L2/L3 miss breakdown
perf stat -e \
    L1-dcache-load-misses,\
    L1-dcache-loads,\
    L2-dcache-load-misses,\
    LLC-load-misses,\
    LLC-loads \
    ./prog

# Cache miss rate = L1-dcache-load-misses / L1-dcache-loads
# > 5% is concerning; > 20% is severe

# False sharing detection
perf stat -e \
    machine_clears.memory_ordering,\
    mem_load_l3_hit_retired.xsnp_hitm \
    ./prog
2. 缓存行基础知识
  • 缓存行大小:在 x86-64、ARM(大多数平台)上为 64 字节
  • L1 缓存:32–64 KB,延迟约为 4 个周期
  • L2 缓存:256 KB–1 MB,延迟约为 12 个周期
  • L3 缓存:6–64 MB,延迟约为 40 个周期
  • 主存:延迟约为 200–300 个周期
// Check cache line size
long cache_line = sysconf(_SC_LEVEL1_DCACHE_LINESIZE);

// Align data to cache line
struct alignas(64) HotData {
    int counter;
    // ... 60 bytes of data that fit in one line
};

// C
typedef struct {
    int x;
} __attribute__((aligned(64))) AlignedData;
3. AoS 与 SoA 数据布局
// AoS (Array of Structures) — default layout
struct Particle {
    float x, y, z;     // position (12 bytes)
    float vx, vy, vz;  // velocity (12 bytes)
    float mass;         // (4 bytes)
    int   flags;        // (4 bytes)
};
Particle particles[N];  // Bad for loops that only need position

// Problem: accessing particles[i].x loads x,y,z,vx,vy,vz,mass,flags
// But we only need x,y,z → 75% of loaded data is wasted

// SoA (Structure of Arrays) — cache-friendly for SIMD + sequential access
struct ParticlesSoA {
    float *x, *y, *z;
    float *vx, *vy, *vz;
    float *mass;
    int   *flags;
};

// Accessing x[i] for i=0..N loads 16 consecutive x values → 0% waste
// Also auto-vectorizes better
4. 常见的缓存不友好模式
// BAD: random access (linked list traversal)
Node *node = head;
while (node) {
    process(node->data);
    node = node->next;  // pointer chasing = cache miss per node
}

// BETTER: pool allocate nodes contiguously
// Or: rewrite as contiguous array with indices

// BAD: stride > cache line in matrix traversal
for (int i = 0; i < N; i++)
    for (int j = 0; j < M; j++)
        sum += matrix[j][i];  // column-major access on row-major array

// GOOD: row-major access
for (int i = 0; i < N; i++)
    for (int j = 0; j < M; j++)
        sum += matrix[i][j];

// BAD: large struct with hot + cold fields
struct Record {
    int id;           // hot: accessed every iteration
    char name[128];   // cold: accessed rarely
    int value;        // hot
    char desc[256];   // cold
};

// GOOD: separate hot and cold data
struct RecordHot { int id; int value; };
struct RecordCold { char name[128]; char desc[256]; };
RecordHot hot_data[N];
RecordCold cold_data[N];
5. 伪共享

当两个线程写入共享同一缓存行的不同变量时,就会发生伪共享,导致缓存行不断失效。

// BAD: counters likely on same cache line (8 bytes each, line = 64 bytes)
int counter_a;  // thread A's counter
int counter_b;  // thread B's counter

// Both on the same cache line → every write invalidates the other thread's cache

// GOOD: pad to separate cache lines
struct alignas(64) PaddedCounter {
    int value;
    char padding[60];  // Ensure next counter is on different cache line
};

PaddedCounter counters[NUM_THREADS];
// Thread i: counters[i].value++

// C++ standard approach
struct alignas(std::hardware_destructive_interference_size) PaddedCounter {
    int value;
};
6. 预取

使用手动预取提示来隐藏内存延迟:

#include <immintrin.h>  // or <xmmintrin.h>

// Prefetch for read (locality 0=non-temporal, 3=high temporal)
__builtin_prefetch(ptr, 0, 3);  // prefetch for read, high locality
__builtin_prefetch(ptr, 1, 3);  // prefetch for write, high locality

// SSE prefetch (x86)
_mm_prefetch((char*)ptr, _MM_HINT_T0);   // L1
_mm_prefetch((char*)ptr, _MM_HINT_T1);   // L2
_mm_prefetch((char*)ptr, _MM_HINT_T2);   // L3
_mm_prefetch((char*)ptr, _MM_HINT_NTA);  // non-temporal (streaming)

// Typical pattern: prefetch N iterations ahead
#define PREFETCH_DIST 8
for (int i = 0; i < N; i++) {
    if (i + PREFETCH_DIST < N)
        __builtin_prefetch(&data[i + PREFETCH_DIST], 0, 3);
    process(data[i]);
}

预取规则:

  • 预取过早 = 缓存可能在使用前被逐出
  • 预取过晚 = 没有收益
  • 预取距离 = 内存延迟 / 每次迭代耗时(通常为 8–32 个元素)
7. 缓存友好型算法设计
// Loop blocking / tiling for matrix operations
// Process cache-fitting blocks instead of full rows/columns
#define BLOCK 64  // tuned to L1 cache size

void matrix_mult_blocked(float *C, float *A, float *B, int N) {
    for (int i = 0; i < N; i += BLOCK)
    for (int k = 0; k < N; k += BLOCK)
    for (int j = 0; j < N; j += BLOCK)
    // Inner block fits in L1 cache
    for (int ii = i; ii < i + BLOCK && ii < N; ii++)
    for (int kk = k; kk < k + BLOCK && kk < N; kk++)
    for (int jj = j; jj < j + BLOCK && jj < N; jj++)
        C[ii*N+jj] += A[ii*N+kk] * B[kk*N+jj];
}

有关 perf 缓存事件参考和伪共享检测模式,请参阅 references/cache-counters.md。

相关技能

  • 使用 skills/profilers/linux-perf 进行 perf stat 和 perf record 缓存测量
  • 使用 skills/profilers/valgrind — cachegrind 可模拟缓存行为
  • 使用 skills/low-level-programming/simd-intrinsics — SoA 布局可与 SIMD 向量化配合使用
  • 在并发场景中检测伪共享,请使用 skills/low-level-programming/memory-model

评论

支持 Markdown