[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -4,112 +4,173 @@ title: Flame Graphs
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-REINFORCE-WIKI-DEV-FLAME-GRAPHS, 플레임 그래프, Flame Graphs, 고드름 그래프, Icicle Graphs, 프로파일링 시각화]
|
||||
aliases: [Flamegraph, Stack Trace Visualization, Brendan Gregg Flame Graph]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [Profiling, Visualization, Performance, Analysis, Runtime]
|
||||
raw_sources: [Datacollector_Export_2026-05-02]
|
||||
last_reinforced: 2026-05-02
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [profiling, performance, observability, perf, ebpf]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: rust
|
||||
framework: perf-pyspy-pprof
|
||||
---
|
||||
|
||||
# [[플레임 그래프를 활용한 호출 스택 시각화 (Flame Graphs)]]
|
||||
# Flame Graphs
|
||||
|
||||
## 1. 개요
|
||||
플레임 그래프(Flame Graph)와 고드름 그래프(Icicle Graph)는 소프트웨어 프로파일러를 통해 수집된 호출 스택(Call Stack) 데이터를 시각화하는 도구이다. 시스템이 실행되는 동안 어떤 함수가 가장 많이 호출되었고, 어디에서 시간을 많이 소비했는지를 한눈에 파악할 수 있게 하여 성능 최적화뿐만 아니라 코드베이스의 핵심 실행 경로(Hot path)를 이해하는 데 강력한 통찰을 제공한다.
|
||||
## 매 한 줄
|
||||
> **"매 stack trace 의 SVG-ified hierarchy"**. Brendan Gregg (2011) 가 만든 매 visualization — 매 x축은 alphabetical (NOT time), 매 y축은 stack depth, 매 width 는 sample count. 매 hot path 가 매 wide flat plateau 로 즉시 보임. 매 2026 현재 perf, eBPF, py-spy, async-profiler, pprof, Pyroscope 등 매 모든 profiler 가 native output.
|
||||
|
||||
## 2. 시각적 구조와 의미
|
||||
- **X축 (너비)**: 함수 호출의 빈도 또는 소비된 시간의 총량을 의미한다. 막대가 넓을수록 해당 함수가 더 많은 자원을 사용했음을 나타낸다. (알파벳 순서로 나열될 뿐, 시간 순서가 아님에 유의)
|
||||
- **Y축 (높이)**: 호출 스택의 깊이를 나타낸다. 아래에서 위로(플레임) 또는 위에서 아래로(고드름) 갈수록 중첩된 함수 호출을 의미한다.
|
||||
- **색상**: 일반적으로 의미는 없으나, 모듈별 또는 함수 유형별로 구분하여 시각적 인지도를 높이는 데 사용된다.
|
||||
## 매 핵심
|
||||
|
||||
## 3. 실전 적용 가치
|
||||
- **코드 해독의 나침반**: 수만 개의 함수 중 실제 워크로드에서 가장 빈번하게 실행되는 '살아있는 코드'를 즉각 식별하여, 분석 우선순위를 정하는 로드맵으로 활용.
|
||||
- **성능 병목 지점(Hotspot) 발견**: 예상치 못한 반복 호출이나 긴 대기 시간을 유발하는 지점을 시각적으로 포착하여 리팩토링 포인트 발굴.
|
||||
- **실제 실행 기반의 팩트 체크**: 개발자의 의도나 문서에 명시된 흐름이 아닌, 런타임에 실제로 일어나는 동작을 객관적으로 증명.
|
||||
### 매 읽는 법
|
||||
- **Width = time spent** (sample count proportional). 매 wide = hot.
|
||||
- **Y = stack depth**. 매 bottom = entry, top = leaf.
|
||||
- **Color = arbitrary** (typically random hue per function — visual separation only).
|
||||
- **Plateau at top** = leaf function 의 CPU bound.
|
||||
- **Tower** = deep call chain (recursion 또는 framework overhead).
|
||||
|
||||
## 4. 트레이드오프 및 주의사항
|
||||
- **관찰 오버헤드**: 프로파일링 데이터 수집 과정에서 시스템 성능이 저하될 수 있으므로, 프로덕션 환경에서는 샘플링 기법을 적절히 조절해야 함.
|
||||
- **해석의 오해**: X축의 너비가 단순히 '함수 실행 속도'가 아님을 인지해야 한다. (함수 자체의 실행 시간뿐 아니라 자식 함수들의 합산 시간이 포함됨)
|
||||
- **비동기 흐름의 제약**: 이벤트 루프나 비동기 콜백이 많은 환경에서는 호출 스택이 파편화되어 그래프가 복잡해질 수 있으며, 이를 추적하기 위한 특화된 도구 필요.
|
||||
### 매 variant
|
||||
- **CPU flame graph**: 매 on-CPU sample 만 — classic.
|
||||
- **Off-CPU flame graph**: 매 blocked time (I/O, lock wait) — 매 latency 분석.
|
||||
- **Differential flame graph**: 매 두 profile 의 diff — red = slower, blue = faster.
|
||||
- **Icicle (inverted)**: top-down — 매 entry-point 분석에 좋음.
|
||||
- **Continuous profiling**: 매 Pyroscope / Grafana Phlare 가 매 production 에 항상 켜짐.
|
||||
|
||||
## 5. 지식 연결 (Related)
|
||||
- [[Dynamic_Behavior_Tracking]]: 플레임 그래프의 기반이 되는 동적 분석 데이터 수집 기법.
|
||||
- [[Profiler_Techniques]]: 그래프를 생성하기 위한 프로파일링 도구 활용법.
|
||||
- [[Performance_Optimization]]: 그래프 분석 결과를 바탕으로 수행하는 실질적인 개선 활동.
|
||||
### 매 도구 매핑
|
||||
1. **Linux native**: `perf record -F 99 -g` + Brendan Gregg's FlameGraph perl script.
|
||||
2. **eBPF**: `bcc/profile`, `parca-agent` — kernel + user 통합.
|
||||
3. **Python**: `py-spy record -o flame.svg --pid $PID`.
|
||||
4. **JVM**: `async-profiler -e cpu -d 30 -f flame.html $PID`.
|
||||
5. **Go**: `go tool pprof -http=:8080 cpu.prof` (built-in flame graph).
|
||||
6. **Node.js**: `0x` or `clinic flame`.
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
- **정보 상태**: 검증 완료 (Verified)
|
||||
- **출처 신뢰도**: A
|
||||
- **검토 이유**: 추측이 아닌 데이터 기반의 시스템 해독과 성능 개선을 위한 시각적 분석 표준 정립.
|
||||
## 💻 패턴
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
### Linux perf → flame graph
|
||||
```bash
|
||||
# 1. Sample 99 Hz for 30s, capture stacks
|
||||
sudo perf record -F 99 -a -g -- sleep 30
|
||||
|
||||
> *(TODO: 한 문장으로 핵심 통찰을 작성. "X는 Y 조건에서 Z 효과를 낸다" 구조 권장.)*
|
||||
# 2. Convert to folded format
|
||||
sudo perf script | \
|
||||
~/FlameGraph/stackcollapse-perf.pl > out.folded
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
# 3. Render SVG
|
||||
~/FlameGraph/flamegraph.pl out.folded > flame.svg
|
||||
|
||||
**추출된 패턴:**
|
||||
> *(TODO)*
|
||||
|
||||
**세부 내용:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
|
||||
- **과거 데이터와의 충돌:** 없음
|
||||
- **정책 변화:** 없음
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
|
||||
- **Parent:** [[10_Wiki/Topics]]
|
||||
- **Related:** *(TODO: 최소 2개)*
|
||||
- **Opposite / Trade-off:** *(TODO)*
|
||||
- **Raw Source:** 직접 입력
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
# Open in browser → click to zoom, search regex highlights
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Differential flame graph (before/after)
|
||||
```bash
|
||||
~/FlameGraph/stackcollapse-perf.pl < before.perf > before.folded
|
||||
~/FlameGraph/stackcollapse-perf.pl < after.perf > after.folded
|
||||
~/FlameGraph/difffolded.pl before.folded after.folded | \
|
||||
~/FlameGraph/flamegraph.pl --negate > diff.svg
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Continuous profiling with Pyroscope (Go)
|
||||
```go
|
||||
import "github.com/grafana/pyroscope-go"
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
func main() {
|
||||
pyroscope.Start(pyroscope.Config{
|
||||
ApplicationName: "checkout-service",
|
||||
ServerAddress: "http://pyroscope:4040",
|
||||
Logger: pyroscope.StandardLogger,
|
||||
Tags: map[string]string{"region": "us-west-2"},
|
||||
ProfileTypes: []pyroscope.ProfileType{
|
||||
pyroscope.ProfileCPU,
|
||||
pyroscope.ProfileAllocObjects,
|
||||
pyroscope.ProfileInuseObjects,
|
||||
},
|
||||
})
|
||||
runServer()
|
||||
}
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### py-spy on running Python service
|
||||
```bash
|
||||
# 30s sample, draw flame graph
|
||||
py-spy record -o flame.svg --pid 12345 --duration 30 --rate 100
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
# Native + Python frames combined
|
||||
py-spy record -o flame.svg --pid 12345 --native
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
# Top-like live view
|
||||
py-spy top --pid 12345
|
||||
```
|
||||
|
||||
### async-profiler for JVM
|
||||
```bash
|
||||
# CPU profile (30s) → flamegraph HTML
|
||||
./profiler.sh -e cpu -d 30 -f flame.html $(jps | grep MyApp | awk '{print $1}')
|
||||
|
||||
# Allocation profile
|
||||
./profiler.sh -e alloc -d 60 -f alloc.html $PID
|
||||
|
||||
# Wall-clock (off-CPU + on-CPU)
|
||||
./profiler.sh -e wall -t -d 30 -f wall.html $PID
|
||||
```
|
||||
|
||||
### Off-CPU flame graph (eBPF / bcc)
|
||||
```bash
|
||||
# Capture off-CPU stacks (blocked time) for 30s
|
||||
sudo /usr/share/bcc/tools/offcputime -df -p $PID 30 > offcpu.folded
|
||||
~/FlameGraph/flamegraph.pl --color=io --title="Off-CPU" \
|
||||
offcpu.folded > offcpu.svg
|
||||
```
|
||||
|
||||
### pprof flame graph (Go built-in)
|
||||
```go
|
||||
import _ "net/http/pprof"
|
||||
|
||||
go func() { http.ListenAndServe("localhost:6060", nil) }()
|
||||
|
||||
// Then on dev machine:
|
||||
// go tool pprof -http=:8080 http://service:6060/debug/pprof/profile?seconds=30
|
||||
// → opens browser, click "View" → "Flame Graph"
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Production continuous | Pyroscope / Grafana Phlare / Polar Signals |
|
||||
| Linux ad-hoc | perf + FlameGraph |
|
||||
| Python | py-spy (zero-instrumentation) |
|
||||
| JVM | async-profiler (allocation + CPU + wall) |
|
||||
| Go | built-in pprof + go tool pprof |
|
||||
| Node | 0x or clinic flame |
|
||||
| Latency / blocked | Off-CPU flame graph (eBPF) |
|
||||
|
||||
**기본값**: 매 production 에 Pyroscope + 매 dev 에 native profiler.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Profiling]] · [[Performance Engineering]]
|
||||
- 변형: [[Icicle Graphs]] · [[Differential Flame Graph]] · [[Off-CPU Flame Graph]]
|
||||
- 응용: [[Performance Tuning]] · [[Continuous Profiling]] · [[SRE]]
|
||||
- Adjacent: [[perf]] · [[eBPF]] · [[pprof]] · [[Pyroscope]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 flame graph 의 hot frame 식별 + optimization 제안, folded text → 자연어 summary, differential interpretation.
|
||||
**언제 X**: 매 visual exact pixel reading — 매 SVG 자체 사용.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Sampling rate too low**: 매 19 Hz — 매 short hot function miss. 매 99 Hz 표준.
|
||||
- **Without -g (no callgraphs)**: 매 perf record -g 누락 — 매 frames frame 만 보임.
|
||||
- **No frame pointers (Go ≤1.20, glibc)**: 매 stack unwind 실패 — `-fno-omit-frame-pointer` 또는 DWARF.
|
||||
- **Reading width as time order**: 매 x축은 time 의 X — alphabetical sort.
|
||||
- **Production profiling once a year**: 매 continuous 의 가치를 놓침.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Brendan Gregg 2011, Pyroscope/Grafana Labs 2026).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — flame graph reading guide + perf/py-spy/pprof recipes |
|
||||
|
||||
Reference in New Issue
Block a user