К основному содержанию
скилл Claude Code CX Codex Cursor GitHub Copilot

performance-optimization · gamedev-skills — скилл для Claude Code: поиск узких мест

Скилл учит искать узкое место в игре по профайлеру движка, а не по догадке, и даёт набор правок: пулы объектов, батчинг, отказ от лишних аллокаций.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill performance-optimization -a claude-code
Открыть на GitHub

Что делает performance-optimization

Скилл задаёт порядок работы с производительностью: сначала замер в профайлере движка, потом одна правка самого дорогого участка, потом повторный замер на той же сцене и железе. Метод не привязан к конкретному движку, поэтому подойдёт и для Godot, и для Unity с Unreal. Внутри — цикл из шагов, разбор бюджета кадра и приёмы вроде пула объектов и сокращения draw calls.

Профайлеры расписаны по движкам. В Godot это вкладки Profiler, Visual Profiler и Monitors плюс вызовы Performance.get_monitor, в Unity окно Profiler с Frame Debugger, в Unreal консольные stat unit и stat scenerendering. Для стоимости симуляции есть смежный скилл physics-tuning. Настройки рендера и экспорта остаются за скиллами конкретных движков.

Два условия, без которых метод не сработает. Нужна воспроизводимая худшая сцена: «иногда тормозит» измерить нельзя. Мерить стоит на релизной сборке, потому что редактор и debug искажают картину. Правило автора прямое: не оптимизировать код, который вы не замерили, ведь правки вслепую обычно бьют мимо.

Какие задачи решает

  • найти, что именно съедает кадр в конкретной сцене
  • убрать рывки от сборки мусора в C#
  • перевести пули и частицы на пул объектов
  • сократить draw calls на сцене с кучей перекрывающихся спрайтов
  • задать бюджеты кадра и ассетов, чтобы выигрыш не откатился назад

Примеры запросов агенту

  • На босс-файте проседает FPS: открой профайлер, скажи, CPU или GPU виноват, и предложи правку.
  • Переведи пули и частицы на пул объектов и замерь кадр до и после.
  • Добавь в проверку бюджеты по подсистемам и потолок draw calls, чтобы регрессия ловилась сразу.

Как установить performance-optimization

1Через Skills CLI (Vercel)

npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill performance-optimization -a claude-code

2Вручную: положить файлы

~/.claude/skills/performance-optimization/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/performance-optimization/

Из того же набора40

Весь набор →
game-feel gamedev-skills Скилл учит агента добавлять отклик к игровым действиям: тряску камеры, стоп-кадр, твины с easing, сквош и отброс. Для случаев, когда механика работает, но ощущается ватной. Claude Code CX Codex Cursor +1 9 400установок game-ui-ux gamedev-skills Архитектурный скилл для создания адаптивных игровых интерфейсов, стека экранов и навигации с геймпада без покадрового опроса состояния. Claude Code CX Codex Cursor +1 9 200установок level-design gamedev-skills Помогает спроектировать игровой уровень от блокута до плейтеста: маршруты, темп, препятствия и столкновения. Нужен при работе с whitebox, критическим путём и геймплейными комнатами. Claude Code CX Codex Cursor +1 7 500установок camera-systems gamedev-skills Рецепты для игровых камер в 2D и 3D: плавное следование, мёртвые зоны, опережение движения и обработка столкновений для Godot и Unity. Claude Code CX Codex Cursor +1 7 100установок audio-design gamedev-skills Скилл учит раскладывать игровой звук по шинам, глушить музыку под голос и собирать адаптивный саундтрек слоями. Примеры кода — на GDScript под Godot 4.7, с пометками для Unity. Claude Code CX Codex Cursor +1 7 100установок game-ai gamedev-skills Помогает проектировать логику врагов и NPC: конечные автоматы, деревья поведения, алгоритмы руления и поиск пути A*. Пригодится при сборке поведения ботов для любого движка. Claude Code CX Codex Cursor +1 7 100установок input-systems gamedev-skills Архитектура игровых управлений: отображение клавиш на действия, перекоординирование с проверкой конфликтов, поддержка клавиатуры, геймпада и сенсора, мёртвые зоны, буферизация и coyote time. Claude Code CX Codex Cursor +1 6 800установок procedural-gen gamedev-skills Генерирует уровни и таблицы лута по сиду на основе детерминированных алгоритмов. Пригодится для процедурного контента без ручной расстановки. Claude Code CX Codex Cursor +1 6 800установок

Другие версии performance-optimization

Похожие

curves-and-paths phaserjs Скилл для работы с кривыми, сплайнами, безье и путями в Phaser 4. Помогает рисовать пути, получать точки вдоль них и заставлять спрайты двигаться по заданной траектории. Claude Code CX Codex Cursor +1 750установок v3-to-v4-migration phaserjs Помогает обновить проект игры с Phaser 3 до Phaser 4. Разбирает несовместимые изменения рендерера, перенос масок в фильтры и замену tintFill. Claude Code CX Codex Cursor +1 711установок unity-developer rmyndharis Скилл для разработки игр на Unity 6 LTS с оптимизацией производительности, настройкой конвейеров рендеринга и кроссплатформной сборкой. Помогает писать C# код, настраивать URP/HDRP и решать проблемы с физикой и ассетами. Claude Code CX Codex Cursor +1 3 000установок orbit-card heygen-com Скилл для встраивания готового 10-секундного 3D-блока HyperFrames: карточка фичи облетает сферу из точек по траектории камеры из Blender. Claude Code CX Codex Cursor +1 9 800установок sdf earthtojake Скилл создаёт и проверяет SDFormat-файлы для моделей и миров, а затем помогает подготовить их к передаче в симулятор. Claude Code CX Codex Cursor +1 10 500установок urdf earthtojake Скилл помогает создавать, проверять и отлаживать описания роботов в формате URDF. Пригодится для работы со звеньями, сочленениями и геометрией. Claude Code CX Codex Cursor +1 10 400установок hatch-pet официальный openai Создаёт и упаковывает анимированных питомцев и спрайт-листы для Codex. Пригодится, когда нужен персонаж по описанию, изображению или фирменным ориентирам. Claude Code CX Codex Cursor +1 3 300установок gcode earthtojake Нарезает модели STL, 3MF и OBJ в G-code через OrcaSlicer. Подходит, когда нужно подготовить файл для печати без подключения к принтеру. Claude Code CX Codex Cursor +1 9 500установок

Вопросы о performance-optimization

Как установить performance-optimization в Claude Code?

Выполните npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill performance-optimization -a claude-code. Скилл появится в ~/.claude/skills/performance-optimization/SKILL.md.

Что делает performance-optimization?

Ведёт от замера к правке: прочитать кадр в профайлере, найти узкое место на стороне CPU или GPU, починить самый дорогой участок и перемерить на той же сцене. Плюс общие приёмы: пулы, батчинг, меньше аллокаций.

Чем это отличается от physics-tuning?

physics-tuning разбирает дрожание физики, туннелирование и шаг симуляции. Здесь общий метод замера кадра и правок рендера или логики.

Исходный текст

SKILL.md · Apache-2.0
---
name: performance-optimization
description: >
  Find and fix game performance problems methodically — measure with the engine profiler first,
  reason about the frame-time budget, locate the CPU-vs-GPU bottleneck, then apply the right fix:
  object pooling, draw-call batching, fewer allocations/GC spikes, and asset budgets. Engine-
  neutral method that pairs with each engine's profiler. Use when the user mentions performance,
  optimize, low/dropping FPS, frame drops, stutter, lag, profiler, frame budget, draw calls,
  batching, garbage collection/GC spikes, object pooling, or "the game runs slow".
---

# Performance optimization

Performance work is a measurement discipline, not a bag of tricks. The method is always the
same: **profile → find the one bottleneck → fix that → measure again**. This skill teaches that
loop and the highest-leverage fixes (pooling, batching, allocation control, asset budgets), and
points you at each engine's profiler. It pairs with `physics-tuning` for simulation cost.

## When to use

- Use when the frame rate is low or uneven, the game stutters/hitches, or it must hit a target
  (60 FPS desktop, 30/60 mobile) and currently doesn't.
- Use to decide *what* to optimize: profile, read the frame budget, and identify whether the CPU
  or GPU is the bottleneck before changing any code.
- Use to apply specific fixes: object pooling, draw-call/batch reduction, removing per-frame
  allocations and GC spikes, and setting asset budgets.

**When *not* to use:** for physics jitter/tunneling/timestep specifically, use `physics-tuning`.
For the engine's concrete profiler UI and rendering settings, use that
engine skill (`godot-export` covers some build settings; engine cores cover the rest). This skill
is the cross-engine method and the shared fixes.

## The golden rule: measure first, never guess

Most performance "fixes" applied without profiling target the wrong thing and add complexity for
no gain. **Do not optimize code you have not measured.** Open the profiler, find the single
biggest cost in a representative scene on representative hardware, and fix that. Re-measure to
confirm the fix helped before moving on. Profile a **release/optimized build** where it matters —
editor and debug builds lie (editor overhead, no compiler optimization).

## Core workflow

1. **Define the target and reproduce.** State the goal (e.g. 60 FPS = 16.67 ms/frame) and find a
   repeatable worst-case scene. "Sometimes slow" is unfixable; a reproducible spike is fixable.
2. **Profile before touching code.** Run the engine profiler and read the frame: total frame
   time, and the split between CPU (game logic, physics, scripts) and GPU (rendering).
3. **Find the bottleneck — CPU or GPU.** If GPU time ≫ CPU, attack draw calls/overdraw/shaders/
   resolution. If CPU time dominates, attack scripts/physics/allocations. Fixing the wrong side
   does nothing.
4. **Fix the single biggest cost.** Prefer an **algorithmic** win (do less work, cache, spatial
   partition, run less often) over micro-optimizing a hot line. Apply the matching shared fix
   (pooling, batching, allocation removal).
5. **Re-measure on the same scene/hardware.** Confirm the number moved. Keep or revert based on
   data, not intuition.
6. **Set budgets so it stays fixed.** Per-frame ms budgets per subsystem, plus asset budgets
   (texture sizes, triangle counts, draw-call ceilings); add a perf check to verification.
7. **Report measured numbers.** State before/after frame time, the bottleneck found, and the fix
   — never "should be faster". If you could only measure in-editor, say so.

## Patterns

### 1. Frame budget math (turn "feels slow" into a number)

```text
target FPS → frame budget:   60 FPS = 16.67 ms   |   30 FPS = 33.3 ms   |   120 FPS = 8.33 ms
The WHOLE frame (CPU sim + render submit + GPU) must fit the budget; the GPU runs in parallel,
so the slower of CPU-frame and GPU-frame sets your FPS. Allocate sub-budgets, e.g. @60 FPS:
  gameplay/scripts ~5 ms · physics ~3 ms · rendering(CPU submit) ~4 ms · UI/other ~2 ms · slack.
If one subsystem blows its slice, that's your target — not whatever you assumed.
```

### 2. Measure with the engine profiler (do this before any fix)

```text
Godot 4.7     : Debugger ▸ Profiler (script/physics time), Visual Profiler (CPU vs GPU render time
                per pass) and Monitors tab (FPS, draw calls, memory).
                In code: Performance.get_monitor(Performance.TIME_PROCESS) returns SECONDS
                (× 1000 for ms); Performance.RENDER_TOTAL_DRAW_CALLS_IN_FRAME for draw calls.
Unity 6.3 LTS : Profiler window (CPU/GPU/Memory/Rendering modules) + Frame Debugger for draw calls.
                In code: ProfilerRecorder on "CPU Main Thread Frame Time" / "GPU Frame Time"
                (release players need Frame Timing Stats enabled in Player Settings).
Unreal 5.8    : `stat unit` (Frame / Game / Draw / RHIT / GPU ms), `stat fps`,
                `stat scenerendering` (draw calls); Unreal Insights for deep traces.
# Read the split: Game = gameplay thread, Draw = render thread (both CPU), GPU = the graphics card.
# Whichever is closest to Frame is the bottleneck; that decides the fix.
```

### 3. Object pooling (stop allocating/freeing in hot loops)

```gdscript
# Bullets, particles, enemies, damage numbers: reuse a fixed set instead of instantiate()/free()
# every frame — that thrashes memory and (in C#) feeds the GC.
var _pool: Array[Node2D] = []                     # Node3D for 3D; both have `visible`
func acquire() -> Node2D:
    var n: Node2D = _pool.pop_back() if not _pool.is_empty() else bullet_scene.instantiate()
    n.set_process(true); n.visible = true
    return n
func release(n: Node2D) -> void:
    n.set_process(false); n.visible = false       # disable + hide; DON'T free
    _pool.append(n)                                # back to the pool for reuse
# RIGHT: pre-warm the pool at load; reuse. WRONG: instantiate()/queue_free() per shot.
```

### 4. Cut draw calls (the most common GPU-side win)

```text
Draw calls and render-state changes (material/shader/texture/blend switches) cost CPU submit time;
thousands of them make the render thread the bottleneck. 2D batchers merge runs of sprites that
share state (most bind several textures per batch), so ordering and atlasing decide the count.
- Atlas textures and share materials so sprites/meshes batch into one call.
- Identical meshes → GPU instancing (Unity; under URP/HDRP the SRP Batcher or GPU Resident Drawer
  takes precedence), MultiMesh / MultiMeshInstance (Godot), Instanced Static Mesh (Unreal).
- Static geometry → static batching / baking; mark non-moving objects static.
- Reduce overdraw: limit large overlapping transparent/particle layers (they re-shade pixels).
- Fewer real-time lights/shadows; bake lighting where it doesn't move.
Measure draw calls before and after — the count should drop, and so should GPU frame time.
```

### 5. Kill per-frame allocations (GC spikes = stutter)

```csharp
// Unity 6.3 LTS (C#). Allocating every frame fills the managed heap; the GC then stalls a frame.
// WRONG (new array + scene walk every call):
//   foreach (var e in FindObjectsByType<Enemy>(FindObjectsSortMode.None)) ...  // + LINQ, new[]
// (FindObjectsOfType is obsolete in Unity 6.3; its replacement still allocates.)
// RIGHT: cache references once, reuse buffers, avoid LINQ/boxing in Update.
void Update() {
    _hits = Physics.RaycastNonAlloc(ray, _hitBuffer);   // reuse a preallocated array
    for (int i = 0; i < _hits; i++) { /* ... */ }       // no per-frame allocation
}   // hit order is undefined and a full buffer may miss the nearest hit: size it, sort if needed
// Godot/GDScript: avoid building new arrays/dictionaries every frame in _process; reuse them.
```

## Pitfalls

- **Optimizing without profiling.** The intuitive culprit is usually wrong. Measure first, every
  time.
- **Profiling the editor / a debug build.** Editor overhead and unoptimized code mislead. Profile
  a release build on target hardware for real numbers.
- **Fixing the wrong side.** Micro-optimizing CPU code when the GPU is the bottleneck (or vice
  versa) changes nothing. Check the CPU-vs-GPU split first.
- **Micro-optimizing over algorithm.** Shaving a function when an O(n²) loop or a per-frame
  full-scene query is the real cost. Reduce the work, don't polish it.
- **Instantiate/free in hot loops.** Spawning and destroying bullets/particles every frame causes
  fragmentation and GC spikes. Pool them.
- **Per-frame allocations / LINQ / boxing in `Update`** (C#) feed the GC → periodic hitches.
  Cache and reuse.
- **Draw-call explosion** from unique materials and unbatched sprites/meshes. Atlas, share
  materials, instance, batch.
- **Unity "Enable GPU Instancing" with no effect** under URP/HDRP: the SRP Batcher takes
  precedence for compatible shaders. Check the Frame Debugger; for many identical meshes use the
  GPU Resident Drawer (Forward+, compute-capable APIs, not OpenGL ES).
- **Overdraw** from stacked transparents/particles/full-screen effects re-shading pixels.
- **No budgets.** Without per-subsystem ms and asset ceilings, performance silently regresses;
  enforce them in your build/CI checks.
- **Optimizing too early.** Don't contort a prototype for performance before it's fun or measured.

## References

- For per-engine profiler walkthroughs, the CPU-vs-GPU triage flowchart, a complete pooling
  manager, batching/instancing rules per engine, allocation/GC guidance, LOD/culling, and asset
  budgets (texture sizes, triangle counts, audio, mobile thermals), read
  `references/profiling-and-budgets.md`.

## Related skills

- `physics-tuning` — simulation cost, fixed-step budget, sleeping bodies, broadphase layers.
- `godot-export` — release/build settings that affect measured performance.
- `procedural-gen`, `game-ai` — common CPU hotspots (generation, pathfinding) to budget and defer.
- `roguelike`, `tower-defense`, `survival-crafting` — entity-heavy genres that need pooling/budgets.

© gamedev-skills · Apache-2.0 · gamedev-skills/awesome-gamedev-agent-skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой