Cpu Cache Opt

mohitmishra786/low-level-dev-skills/skills/low-level-programming/cpu-cache-opt

作者 mohitmishra786bdc58472fa9f無授權條款253 個星標收錄於 2026年10月9日更新於 2026年10月9日儲存庫3 個月前更新

CPU cache optimization skill for C/C++ and Rust. Use when diagnosing cache misses, improving data layout for cache efficiency, using perf stat cache counters, understanding false sharing, prefetching, or structuring AoS vs SoA data layouts. Activates on queries about cache misses, cache lines, false sharing, perf cache counters, data layout optimization, prefetch, AoS vs SoA, or L1/L2/L3 cache performance.

AI 產生的概覽

指導 C/C++ 與 Rust 的快取友善程式設計:診斷快取未命中、資料佈局、偽共享與預取。

功能
此技能為 C/C++ 與 Rust 的快取友善程式設計提供指引。內容涵蓋使用 perf stat 計數器量測快取效能、快取行基礎與對齊、AoS 與 SoA 資料佈局轉換、常見的不利快取模式、偽共享的偵測與填充修正、手動預取,以及迴圈分塊等快取友善演算法設計。產出為說明與程式碼範例,而非檔案或指令碼。
適用情境
適用於診斷高快取未命中率、在 AoS 與 SoA 佈局之間做選擇、排查多執行緒程式中的偽共享、套用預取提示,或以 perf 量測 L1/L2/L3 快取行為。面向關注記憶體存取模式的 C/C++ 或 Rust 效能調校工作。
執行需求
不隨附指令碼,僅為說明性內容。依步驟量測需要 Linux 上的 perf 以及已編譯的 C/C++ 或 Rust 程式;程式碼範例使用編譯器內建函式與標準標頭檔。

CPU Cache Optimization

Purpose

Guide agents through cache-aware programming: diagnosing cache misses with perf, data layout transformations (AoS→SoA), false sharing detection and fixes, prefetching, and cache-friendly algorithm design.

Triggers

  • "My program has high cache miss rates — how do I fix it?"
  • "What is false sharing and how do I detect it?"
  • "Should I use AoS or SoA data layout?"
  • "How do I measure cache performance with perf?"
  • "How do I use __builtin_prefetch?"
  • "My multithreaded program is slower than single-threaded due to cache"

Workflow

1. Measure cache performance

bash
# Basic cache countersperf stat -e cache-references,cache-misses,cycles,instructions ./prog
# L1/L2/L3 miss breakdownperf 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 detectionperf stat -e \    machine_clears.memory_ordering,\    mem_load_l3_hit_retired.xsnp_hitm \    ./prog

2. Cache line basics

  • Cache line size: 64 bytes on x86-64, ARM (most platforms)
  • L1 cache: 32–64 KB, ~4 cycles latency
  • L2 cache: 256 KB–1 MB, ~12 cycles latency
  • L3 cache: 6–64 MB, ~40 cycles latency
  • Main memory: ~200–300 cycles latency
c
// Check cache line sizelong cache_line = sysconf(_SC_LEVEL1_DCACHE_LINESIZE);
// Align data to cache linestruct alignas(64) HotData {    int counter;    // ... 60 bytes of data that fit in one line};
// Ctypedef struct {    int x;} __attribute__((aligned(64))) AlignedData;

3. AoS vs SoA data layout

c
// AoS (Array of Structures) — default layoutstruct 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 accessstruct 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. Common cache-unfriendly patterns

c
// 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 traversalfor (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 accessfor (int i = 0; i < N; i++)    for (int j = 0; j < M; j++)        sum += matrix[i][j];
// BAD: large struct with hot + cold fieldsstruct 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 datastruct RecordHot { int id; int value; };struct RecordCold { char name[128]; char desc[256]; };RecordHot hot_data[N];RecordCold cold_data[N];

5. False sharing

False sharing occurs when two threads write to different variables that share a cache line, causing constant cache-line invalidations.

c
// BAD: counters likely on same cache line (8 bytes each, line = 64 bytes)int counter_a;  // thread A's counterint 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 linesstruct 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 approachstruct alignas(std::hardware_destructive_interference_size) PaddedCounter {    int value;};

6. Prefetching

Manual prefetch hints to hide memory latency:

c
#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 8for (int i = 0; i < N; i++) {    if (i + PREFETCH_DIST < N)        __builtin_prefetch(&data[i + PREFETCH_DIST], 0, 3);    process(data[i]);}

Prefetching rules:

  • Prefetch too early = cache evicted before use
  • Prefetch too late = no benefit
  • Prefetch distance = memory latency / time per iteration (typically 8–32 elements)

7. Cache-friendly algorithm design

c
// 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];}

For perf cache event reference and false sharing detection patterns, see references/cache-counters.md [blocked].

Related skills

  • Use skills/profilers/linux-perf for perf stat and perf record cache measurements
  • Use skills/profilers/valgrind — cachegrind simulates cache behaviour
  • Use skills/low-level-programming/simd-intrinsics — SoA layout pairs with SIMD vectorization
  • Use skills/low-level-programming/memory-model for false sharing in concurrent contexts

來源與署名

來源:mohitmishra786/low-level-dev-skills位於skills/low-level-programming/cpu-cache-opt提交bdc5847

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架