프로파일링 기법 개요 — Sampling vs Instrumentation·PGO·LTO
#한 줄 요약
Sampling은 가볍지만 noisy하고, Instrumentation은 정확하지만 무겁습니다. 상황에 맞춰 골라야 합니다.
#Sampling Profiling
주기적 interrupt로 현재 PC를 캡처하는 통계적 추정 방식입니다.
1000 Hz timer interrupt:매 1 ms마다 PC 기록1초 동안 1000 sample주요 hot function = sample 많은 곳#장단점
- 낮은 overhead (1-5%)입니다.
- Production에서 사용할 수 있습니다.
- 외부 sampling tool이므로 코드 수정이 필요 없습니다.
- 짧은 함수 (< 1ms)는 놓칠 수 있습니다.
- Sample size는 sample rate에 시간을 곱한 값입니다.
#대표 도구
- perf (Linux) — 1 kHz 기본입니다.
- gperftools (Google) — user-space입니다.
- Instruments (macOS)
- Visual Studio Profiler (Windows)
#Instrumentation Profiling
각 함수 진입과 exit에 카운터와 시간을 기록합니다.
// 컴파일러가 자동 삽입 (-pg)void func() { __cyg_profile_func_enter(...); // ... __cyg_profile_func_exit(...);}#장단점
- 정확합니다. 모든 호출이 카운트됩니다.
- Call graph가 정확합니다.
- 짧은 함수도 잡힙니다.
- Overhead가 큽니다 (20-200%).
- 측정값이 현실과 다를 수 있습니다 (probe effect).
#대표 도구
- gprof —
-pg로 컴파일합니다. - callgrind (Valgrind) — 시뮬레이션 방식입니다.
- dtrace — 동적 instrumentation입니다.
- eBPF — kernel과 user-space 모두 동적 가능합니다.
#perf — Linux 표준
# Samplingperf record -F 999 -p PID -g -- sleep 30perf report
# Aggregate statsperf stat ./myapp# task-clock, cycles, instructions, cache-misses 등 자동 수집#Flamegraph
perf record -F 99 -g ./appperf script | stackcollapse-perf.pl | flamegraph.pl > out.svgCPU 사용 분포가 시각화되어 hot path를 즉시 인식할 수 있습니다.
#eBPF — 모던 Dynamic Tracing
Linux kernel과 user-space에 bytecode를 주입합니다. 정확하면서 low overhead입니다.
# bpftracebpftrace -e 'tracepoint:syscalls:sys_enter_read { @[comm] = count(); }'
# BCC 도구opensnoop # file opensbiolatency # disk I/O latencyfunclatency # function latencyCSV, flamegraph, histogram을 자동 출력합니다. Brendan Gregg가 추천하는 도구입니다.
#ftrace — Linux Kernel Tracer
echo function > /sys/kernel/debug/tracing/current_tracerecho 'sys_*' > /sys/kernel/debug/tracing/set_ftrace_filterecho 1 > /sys/kernel/debug/tracing/tracing_on
cat /sys/kernel/debug/tracing/traceKernel-only입니다. Function entry/exit와 latency·event tracers를 제공합니다.
#임베디드 — RTOS Tracer
| 도구 | RTOS | 특징 |
|---|---|---|
| Tracealyzer (Percepio) | FreeRTOS·Zephyr·SafeRTOS | 상용이며 강력합니다 |
| SystemView (Segger) | FreeRTOS·embOS·µC/OS | 무료지만 J-Link가 필수입니다 |
| Zephyr Tracing | Zephyr | 내장입니다 |
| CTF (Common Trace Format) | 모든 RTOS | 표준 포맷입니다 |
SEGGER_SYSVIEW_OnTaskStartExec(task);SEGGER_SYSVIEW_OnTaskStopExec();자동 hook과 GUI viewer로 Linux ftrace 같은 시각화가 가능합니다.
#Profile-Guided Optimization (PGO)
# 1. Instrument 컴파일gcc -fprofile-generate -o app app.c
# 2. 실 워크로드 실행 (training)./app < training_data
# 3. profile 데이터 사용 재컴파일gcc -fprofile-use -O3 -o app app.c컴파일러가 hot path를 우대합니다. Branch prediction, inline, register 할당이 모두 최적화됩니다.
#효과
Without PGO: 100 msWith PGO: 85-90 ms (10-15% 개선)- Branch unlikely 자동 hint를 줍니다.
- Hot function이 inline됩니다.
- Layout optimization (hot code clustering)이 적용됩니다.
#Link-Time Optimization (LTO)
gcc -flto -O3 -o app *.c링크 시점에 전체 프로그램을 볼 수 있어서 cross-file inline, DCE, constant propagation이 가능합니다.
#효과
Without LTO: 100 msWith LTO: 90-95 ms (5-10%)With PGO + LTO: 80-85 ms (15-20%)조합하면 순수 algorithmic 변화 없이도 15-20%가 개선됩니다.
#임베디드 적용
arm-none-eabi-gcc -flto -O2 -ffunction-sections -fdata-sections \ -Wl,--gc-sections -o firmware.elf-flto는 link-time optimization을 켭니다.-ffunction-sections -fdata-sections+--gc-sections로 미사용 코드를 제거합니다.- 코드 크기는 10-20% 감소하고 성능은 5-10% 향상됩니다.
#Microbenchmark vs System Benchmark
| Microbench | System | |
|---|---|---|
| 대상 | 단일 함수 | 전체 app |
| Overhead | 작음 | 큼 |
| 결과 활용 | 알고리즘 비교 | 사용자 경험 |
| 위험 | 현실을 반영하지 못합니다 | 어디가 느린지 알 수 없습니다 |
둘 다 필요합니다. System bench로 bottleneck을 식별하고, Microbench로 대안을 비교합니다.
#Profiler Output 해석
#perf report
Samples: 10K of event 'cycles', Event count: 5,200,000,000Overhead Command Shared Object Symbol 35.0% app app [.] hot_function 20.0% app libc.so [.] memcpy 15.0% app [kernel] [k] scheduleSelf vs Cumulative가 중요합니다. self는 그 함수 자체만, cumulative는 호출한 모든 함수를 포함합니다.
#gprof output
% time self cumulative35.00 1.0 1.0 hot_function20.00 0.5 1.5 memcpy_call_chain함수별 시간과 call count가 표시됩니다. Call graph는 별도 섹션으로 나옵니다.
#Inclusive vs Exclusive Time
foo() { for (...) bar(); // 90 ms baz(); // 5 ms return; // 5 ms self}
foo의 inclusive: 100 ms (모든 호출 포함)foo의 exclusive (self): 10 ms (bar·baz 제외)Exclusive (self) time이 큰 함수가 직접 최적화 대상입니다.
#자주 하는 실수
⚠️ Sample rate 너무 낮음
10 Hz로 5초 sampling은 50 sample뿐이라 결론을 낼 수 없습니다. 최소 99 Hz × 30초 이상이 필요합니다.
⚠️ Debug build profile
-O0로 측정한 hot path와 -O2 hot path는 완전히 다릅니다. Release build로 profile해야 합니다.
⚠️ Profile 후 예상 함수 수정
Profile 결과가 예상과 다를 때 진짜 학습이 됩니다. 측정이 답입니다.
⚠️ Production에서 instrumentation
20-200% overhead로 production이 망가집니다. Production에서는 sampling만 사용해야 합니다.
#정리 — Part 1 마무리
- Sampling은 low overhead의 statistical 방식이고, Instrumentation은 accurate하지만 heavy합니다.
- perf는 Linux 표준이고, eBPF는 모던 dynamic tracing입니다.
- SystemView, Tracealyzer는 임베디드 RTOS trace에 씁니다.
- PGO와 LTO를 결합하면 15-20%의 무료 성능을 얻습니다.
- Release build로 profile하고 production에서는 sampling만 사용합니다.
Part 1 (Performance Analysis Fundamentals)이 끝났습니다. Part 2부터는 CPU와 Microarchitecture를 깊이 다룹니다.
#관련 항목
Embedded Performance Engineering · 9 of 57
- 1Embedded Performance Engineering — 임베디드 성능 엔지니어링 시리즈 소개
- 2임베디드 성능 분석 방법론 — Measure → Analyze → Optimize 사이클
- 3성능 지표 정의 — Latency·Throughput·Utilization 분석
- 4성능 측정의 기본 — Wall-Clock·CPU Cycle·Instruction Count
- 5성능 데이터 통계적 분석 — Percentile·Histogram·평균의 함정
- 6실시간 성능 분석 — WCET·Jitter·Deadline Miss 측정
- 7임베디드 벤치마킹 기초 — 재현성·Warmup·노이즈 제거
- 8성능 모델링 — Amdahl·Gustafson·Roofline Model 적용
- 9프로파일링 기법 개요 — Sampling vs Instrumentation·PGO·LTO
- 10CPU 파이프라인 분석 — 5-stage·Cortex-M·Cortex-A 비교
- 11Pipeline Stall 분석 — Data·Structural·Control Hazard·Forwarding
- 12Branch Prediction 분석 — Static·2-bit·BTB·BHT·Mispredict 비용
- 13Speculative Execution 분석 — OoO·Reorder Buffer·Register Renaming
- 14CPU Cache 기초 — L1·L2·L3·Set Associative·Replacement Policy
- 15Cache Miss 3C Model 분석 — Compulsory·Capacity·Conflict
- 16Cache Line 최적화 — Alignment·Prefetch·False Sharing 처리
- 17메모리 대역폭 분석 — STREAM·Roofline·Bus Saturation 측정
- 18SIMD·NEON 활용 — 128-bit Vector·Auto-Vectorization·SVE/SVE2
- 19PMU·HPM 하드웨어 카운터 분석 — 정밀 성능 진단
- 20임베디드 Bus Architecture — AHB·AXI·CHI 진화와 5-Channel
- 21Bus Contention 진단 — Arbitration·QoS·Starvation 측정
- 22DMA 성능 최적화 — Burst·Scatter-Gather·Chain·Cache 일관성
- 23DMA vs CPU Copy 성능 비교 — Break-even·Setup Overhead 실측
- 24Interrupt Latency 분석 — 진입·종료·Tail-Chaining·Late Arrival
- 25Interrupt Storm 처리 — NAPI·Rate-Limit·Polling 전환
- 26MMIO 접근 성능 — Cache Policy·Write-Combining·Volatile·Barrier
- 27Peripheral Clock 분석 — PLL·Divider·Gating·DVFS
- 28Power vs Performance 트레이드오프 — DVFS·Race-to-Idle·Big.LITTLE
- 29Thermal Throttling 분석 — Junction Temp·Trip Point·냉각
- 30CXL Interconnect 분석 — AI 시대 메모리 대역폭 확장
- 31Concurrency 기초 — Concurrency vs Parallelism·Race·Memory Model
- 32False Sharing 진단 — Cache Line Ping-Pong·Padding·측정
- 33Lock Contention 분석 — Wait·Hold·Convoy·측정 기법
- 34Spinlock 성능 분석 — Spin-Wait vs Context Switch·Ticket·MCS
- 35Mutex 성능 분석 — Futex·Adaptive·Priority Inheritance
- 36Reader-Writer Lock 성능 — Reader/Writer Priority·RCU·Seqlock
- 37Lock-Free 자료구조 성능 — CAS·ABA·Hazard Pointer·Epoch Reclamation
- 38Memory Ordering 분석 — Acquire·Release·Seq-Cst·ARM Relaxed Model
- 39Cache Coherency 프로토콜 — MESI·MOESI·Snoop·Directory
- 40SMP 성능 분석 — Per-Core·Affinity·Load Balance·Scalability
- 41Linux perf 기초 — stat·record·report 활용
- 42Linux perf 고급 — Raw Event·Tracepoint·perf script
- 43ftrace 활용 — function·function_graph·latency tracer
- 44eBPF·bpftrace 동적 트레이싱 — 커널 무수정 관측
- 45Flamegraph 분석 — On-CPU·Off-CPU·Differential
- 46ARM DS·Lauterbach 분석 — Hardware Trace 전문 도구
- 47Bare-metal 프로파일링 — GPIO·DWT·SysTick·ITM 활용
- 48NVIDIA Nsight Systems — GPU·NPU 포함 시스템 분석
- 49모던 프로파일러 비교 — Tracy·Hotspot·uftrace·Coz
- 50연속 프로파일링 — Parca·Pixie·Pyroscope·Tetragon
- 51실전 사례 — ISR Latency 100µs Deadline Miss 추적
- 52실전 사례 — Matrix Multiply가 예상의 10배 느린 이유
- 53실전 사례 — 8-core가 4-core를 넘으면 throughput이 떨어지는 이유
- 54실전 사례 — 카메라 1080p 60fps가 30fps로 떨어지는 이유
- 55CXL.mem 지연·대역폭 실측 — Direct·Switch·Pooled 토폴로지 비교
- 56CXL 성능 프로파일링 도구 — cxl-cli·DAMON·perf-mem 활용
- 57실전 사례 — CXL.mem 추가로 LLM inference KV cache 처리량 회복
관련 글
Linux perf 기초 — stat·record·report 활용
Linux perf 표준 도구의 세 가지 핵심 명령. 설치, 권한, 그리고 첫 측정부터 핫스팟 분석까지.
Embedded Performance Engineering — 임베디드 성능 엔지니어링 시리즈 소개
왜 느린가? Cache miss, pipeline stall, bus contention부터 profiling 도구 활용까지. 임베디드 시스템 성능 분석의 모든 것.
CXL 성능 프로파일링 도구 — cxl-cli·DAMON·perf-mem 활용
CXL.mem 환경 성능 도구 — cxl-cli 토폴로지·DAMON page activity·perf-mem로 보는 CXL 트래픽·numastat 통계.