본문으로 건너뛰기
Embedded Performance Engineering · 8/57

프로파일링 기법 개요 — Sampling vs Instrumentation·PGO·LTO

· Hawk · 5분 읽기

#한 줄 요약

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 표준

Terminal window
# Sampling
perf record -F 999 -p PID -g -- sleep 30
perf report
# Aggregate stats
perf stat ./myapp
# task-clock, cycles, instructions, cache-misses 등 자동 수집

#Flamegraph

Terminal window
perf record -F 99 -g ./app
perf script | stackcollapse-perf.pl | flamegraph.pl > out.svg

CPU 사용 분포가 시각화되어 hot path를 즉시 인식할 수 있습니다.

#eBPF — 모던 Dynamic Tracing

Linux kernel과 user-space에 bytecode를 주입합니다. 정확하면서 low overhead입니다.

Terminal window
# bpftrace
bpftrace -e 'tracepoint:syscalls:sys_enter_read { @[comm] = count(); }'
# BCC 도구
opensnoop # file opens
biolatency # disk I/O latency
funclatency # function latency

CSV, flamegraph, histogram을 자동 출력합니다. Brendan Gregg가 추천하는 도구입니다.

#ftrace — Linux Kernel Tracer

Terminal window
echo function > /sys/kernel/debug/tracing/current_tracer
echo 'sys_*' > /sys/kernel/debug/tracing/set_ftrace_filter
echo 1 > /sys/kernel/debug/tracing/tracing_on
cat /sys/kernel/debug/tracing/trace

Kernel-only입니다. Function entry/exitlatency·event tracers를 제공합니다.

#임베디드 — RTOS Tracer

도구RTOS특징
Tracealyzer (Percepio)FreeRTOS·Zephyr·SafeRTOS상용이며 강력합니다
SystemView (Segger)FreeRTOS·embOS·µC/OS무료지만 J-Link가 필수입니다
Zephyr TracingZephyr내장입니다
CTF (Common Trace Format)모든 RTOS표준 포맷입니다
SEGGER_SYSVIEW_OnTaskStartExec(task);
SEGGER_SYSVIEW_OnTaskStopExec();

자동 hook과 GUI viewer로 Linux ftrace 같은 시각화가 가능합니다.

#Profile-Guided Optimization (PGO)

Terminal window
# 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 ms
With PGO: 85-90 ms (10-15% 개선)
  • Branch unlikely 자동 hint를 줍니다.
  • Hot function이 inline됩니다.
  • Layout optimization (hot code clustering)이 적용됩니다.
Terminal window
gcc -flto -O3 -o app *.c

링크 시점에 전체 프로그램을 볼 수 있어서 cross-file inline, DCE, constant propagation이 가능합니다.

#효과

Without LTO: 100 ms
With LTO: 90-95 ms (5-10%)
With PGO + LTO: 80-85 ms (15-20%)

조합하면 순수 algorithmic 변화 없이도 15-20%가 개선됩니다.

#임베디드 적용

Terminal window
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

MicrobenchSystem
대상단일 함수전체 app
Overhead작음
결과 활용알고리즘 비교사용자 경험
위험현실을 반영하지 못합니다어디가 느린지 알 수 없습니다

둘 다 필요합니다. System bench로 bottleneck을 식별하고, Microbench로 대안을 비교합니다.

#Profiler Output 해석

#perf report

Samples: 10K of event 'cycles', Event count: 5,200,000,000
Overhead Command Shared Object Symbol
35.0% app app [.] hot_function
20.0% app libc.so [.] memcpy
15.0% app [kernel] [k] schedule

Self vs Cumulative가 중요합니다. self는 그 함수 자체만, cumulative는 호출한 모든 함수를 포함합니다.

#gprof output

% time self cumulative
35.00 1.0 1.0 hot_function
20.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

  1. 1Embedded Performance Engineering — 임베디드 성능 엔지니어링 시리즈 소개
  2. 2임베디드 성능 분석 방법론 — Measure → Analyze → Optimize 사이클
  3. 3성능 지표 정의 — Latency·Throughput·Utilization 분석
  4. 4성능 측정의 기본 — Wall-Clock·CPU Cycle·Instruction Count
  5. 5성능 데이터 통계적 분석 — Percentile·Histogram·평균의 함정
  6. 6실시간 성능 분석 — WCET·Jitter·Deadline Miss 측정
  7. 7임베디드 벤치마킹 기초 — 재현성·Warmup·노이즈 제거
  8. 8성능 모델링 — Amdahl·Gustafson·Roofline Model 적용
  9. 9프로파일링 기법 개요 — Sampling vs Instrumentation·PGO·LTO
  10. 10CPU 파이프라인 분석 — 5-stage·Cortex-M·Cortex-A 비교
  11. 11Pipeline Stall 분석 — Data·Structural·Control Hazard·Forwarding
  12. 12Branch Prediction 분석 — Static·2-bit·BTB·BHT·Mispredict 비용
  13. 13Speculative Execution 분석 — OoO·Reorder Buffer·Register Renaming
  14. 14CPU Cache 기초 — L1·L2·L3·Set Associative·Replacement Policy
  15. 15Cache Miss 3C Model 분석 — Compulsory·Capacity·Conflict
  16. 16Cache Line 최적화 — Alignment·Prefetch·False Sharing 처리
  17. 17메모리 대역폭 분석 — STREAM·Roofline·Bus Saturation 측정
  18. 18SIMD·NEON 활용 — 128-bit Vector·Auto-Vectorization·SVE/SVE2
  19. 19PMU·HPM 하드웨어 카운터 분석 — 정밀 성능 진단
  20. 20임베디드 Bus Architecture — AHB·AXI·CHI 진화와 5-Channel
  21. 21Bus Contention 진단 — Arbitration·QoS·Starvation 측정
  22. 22DMA 성능 최적화 — Burst·Scatter-Gather·Chain·Cache 일관성
  23. 23DMA vs CPU Copy 성능 비교 — Break-even·Setup Overhead 실측
  24. 24Interrupt Latency 분석 — 진입·종료·Tail-Chaining·Late Arrival
  25. 25Interrupt Storm 처리 — NAPI·Rate-Limit·Polling 전환
  26. 26MMIO 접근 성능 — Cache Policy·Write-Combining·Volatile·Barrier
  27. 27Peripheral Clock 분석 — PLL·Divider·Gating·DVFS
  28. 28Power vs Performance 트레이드오프 — DVFS·Race-to-Idle·Big.LITTLE
  29. 29Thermal Throttling 분석 — Junction Temp·Trip Point·냉각
  30. 30CXL Interconnect 분석 — AI 시대 메모리 대역폭 확장
  31. 31Concurrency 기초 — Concurrency vs Parallelism·Race·Memory Model
  32. 32False Sharing 진단 — Cache Line Ping-Pong·Padding·측정
  33. 33Lock Contention 분석 — Wait·Hold·Convoy·측정 기법
  34. 34Spinlock 성능 분석 — Spin-Wait vs Context Switch·Ticket·MCS
  35. 35Mutex 성능 분석 — Futex·Adaptive·Priority Inheritance
  36. 36Reader-Writer Lock 성능 — Reader/Writer Priority·RCU·Seqlock
  37. 37Lock-Free 자료구조 성능 — CAS·ABA·Hazard Pointer·Epoch Reclamation
  38. 38Memory Ordering 분석 — Acquire·Release·Seq-Cst·ARM Relaxed Model
  39. 39Cache Coherency 프로토콜 — MESI·MOESI·Snoop·Directory
  40. 40SMP 성능 분석 — Per-Core·Affinity·Load Balance·Scalability
  41. 41Linux perf 기초 — stat·record·report 활용
  42. 42Linux perf 고급 — Raw Event·Tracepoint·perf script
  43. 43ftrace 활용 — function·function_graph·latency tracer
  44. 44eBPF·bpftrace 동적 트레이싱 — 커널 무수정 관측
  45. 45Flamegraph 분석 — On-CPU·Off-CPU·Differential
  46. 46ARM DS·Lauterbach 분석 — Hardware Trace 전문 도구
  47. 47Bare-metal 프로파일링 — GPIO·DWT·SysTick·ITM 활용
  48. 48NVIDIA Nsight Systems — GPU·NPU 포함 시스템 분석
  49. 49모던 프로파일러 비교 — Tracy·Hotspot·uftrace·Coz
  50. 50연속 프로파일링 — Parca·Pixie·Pyroscope·Tetragon
  51. 51실전 사례 — ISR Latency 100µs Deadline Miss 추적
  52. 52실전 사례 — Matrix Multiply가 예상의 10배 느린 이유
  53. 53실전 사례 — 8-core가 4-core를 넘으면 throughput이 떨어지는 이유
  54. 54실전 사례 — 카메라 1080p 60fps가 30fps로 떨어지는 이유
  55. 55CXL.mem 지연·대역폭 실측 — Direct·Switch·Pooled 토폴로지 비교
  56. 56CXL 성능 프로파일링 도구 — cxl-cli·DAMON·perf-mem 활용
  57. 57실전 사례 — CXL.mem 추가로 LLM inference KV cache 처리량 회복