cpu-architecture
Use when the user asks why a loop is slow, branch misprediction, cache misses, false sharing, out-of-order execution, memory ordering, SIMD, TLB misses or…
от j4flmao★ 47 звёзд на GitHub
Установить cpu-architecture в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
CPU Architecture and Microarchitecture
Purpose
Code that looks sequential runs on superscalar, out-of-order, speculative cores behind a deep cache hierarchy. Performance problems are usually memory access patterns, unpredictable branches or dependency chains, not instruction counts. This skill explains those mechanisms and how to measure them before changing code.
Agent Protocol
Trigger
"CPU pipeline", "branch prediction", "out-of-order", "superscalar", "cache miss", "false sharing", "memory ordering", "SIMD", "TLB", "performance counters", "perf stat", "microarchitecture".
Input Context
- CPU (vendor, generation) and OS; compiler and flags
- The hot code (from a profiler), data sizes and access pattern
- Existing measurements (time,
perf stat, VTune/uProf/Instruments output)
Output Artifact
Diagnosis tied to a hardware mechanism, measurement commands, and a code change. No file unless requested.
Response Format
Symptom: {what was measured}
Mechanism: {e.g. L2 miss bound, branch mispredicts, dependency chain, false sharing}
Evidence: {counter values / profile lines}
Change: {code or layout change}
Expected effect + how to verify: {counter to re-check}
1. Execution Model
- Pipeline: fetch → decode (x86 instructions → micro-ops, often from a µop cache) → rename/allocate → schedule → execute → retire in program order. Front ends are 4–8+ wide on current cores.
- Out-of-order: instructions whose inputs are ready execute early; a reorder buffer of a few hundred entries retires them in order. Long-latency loads are overlapped with independent work — but only up to ROB/load-buffer capacity.
- Dependency chains limit speed:
sum += a[i]serialises on floating-point add latency (~3–4 cycles); multiple accumulators break the chain:
double s0 = 0, s1 = 0, s2 = 0, s3 = 0;
for (size_t i = 0; i + 4 <= n; i += 4) { s0 += a[i]; s1 += a[i+1]; s2 += a[i+2]; s3 += a[i+3]; }
double s = (s0 + s1) + (s2 + s3); /* changes FP rounding order: only where acceptable */
2. Branch Prediction
- Predictors learn patterns and history; a mispredict flushes speculative work, costing roughly 10–20+ cycles on modern cores.
- Data-dependent unpredictable branches in hot loops hurt. The classic demonstration: filtering
if (x >= 128)over random bytes is several times faster after sorting the data, because the branch becomes predictable. - Fixes: sort/partition data, make code branchless (
cmov/select, masks, SIMD compares), or restructure so the common case is a straight line. Check that the compiler actually emitted a branchless form. - Indirect branches (virtual calls, switch tables) are predicted too; megamorphic call sites mispredict.
3. Memory Hierarchy
| Level | Typical size per core | Typical latency |
|---|---|---|
| L1D | 32–64 KB (128 KB on Apple P-cores) | ~4–5 cycles |
| L2 | 512 KB–2 MB (shared per cluster on some ARM designs) | ~12–16 cycles |
| L3 / SLC | several MB to 100+ MB shared | ~30–70 cycles |
| DRAM | GBs | ~70–120 ns (hundreds of cycles) |
Numbers vary by chip; measure with a pointer-chasing benchmark if they matter.
- Cache line = 64 bytes on x86 and most ARM cores, 128 bytes on Apple M-series. Access is per line: touching one byte loads 64.
- Hardware prefetchers detect sequential and strided streams; pointer chasing defeats them.
- Layout rules: contiguous arrays over linked structures; structure-of-arrays for loops that touch one field; hot/cold splitting; tile loops (blocking) so the working set fits in L1/L2.
- See
references/cache-hierarchy.mdfor coherence and inclusive/exclusive designs.
4. Coherence and False Sharing
- MESI-family protocols (MESIF on Intel, MOESI on AMD) keep caches coherent per line. Two cores writing different variables in the same line ping-pong it between caches (false sharing).
- Fix: pad/align per-thread data to the line size (
alignas(64)orstd::hardware_destructive_interference_size), or accumulate thread-locally and combine at the end.
5. Memory Ordering
- x86-64 is TSO: stores are not reordered with other stores, loads not with loads, but a later load can pass an earlier store to a different address (store buffer).
- ARM64 is weakly ordered: loads and stores can be reordered; use acquire/release (
LDAR/STLR) or barriers (DMB). - Write portable code with the language memory model (
std::atomicwithmemory_order_acquire/release, RustOrdering), never by relying on x86 behaviour.
6. SIMD
- x86: SSE (128-bit), AVX/AVX2 (256-bit), AVX-512 (512-bit, available on server parts and AMD Zen 4/5; absent on most Intel client chips since Alder Lake). ARM: NEON (128-bit), SVE/SVE2 (scalable vectors, e.g. Graviton, Neoverse cores).
- Let the compiler auto-vectorise first (
-O3 -march=nativefor local tests, explicit target levels like-march=x86-64-v3for distribution); check with-Rpass=loop-vectorize(Clang) or-fopt-info-vec(GCC). - Obstacles
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
- references/cache-hierarchy.md
- references/cpu-cache-optimization.md
- references/tlb-and-paging.md
FAQ
Что делает скилл cpu-architecture?
Use when the user asks why a loop is slow, branch misprediction, cache misses, false sharing, out-of-order execution, memory ordering, SIMD, TLB misses or perf stat hardware counters. Produces measured, microarchitecture-aware optimisations for x86-64 and ARM64. Not for compiler internals (use compiler-design) or kernel design (use kernel-development).
Как установить скилл cpu-architecture?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл cpu-architecture запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
frontend-design
AnthropicGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making…
webapp-testing
AnthropicToolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing…
brand-guidelines
AnthropicApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand…
web-artifacts-builder
AnthropicSuite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn/ui). Use…