측정 없이 최적화 X
최적화 첫 번째 룰 — profile 먼저. 측정 없이 시작도 안 느렸던 코드 빠르게 하느라 시간 보냄. Python 이 stdlib 도구 가짐 — 전체 프로그램에서 시간 어디로 가는지엔 cProfile, 이 snippet 얼마나 빠른지엔 timeit.
cProfile — hot spot 찾기
python -m cProfile -s cumulative script.py 가 스크립트 실행 + cumulative time 정렬 함수 호출 timing 출력. 상단 항목이 최적화 노력 집중할 곳. cProfile 이 오버헤드 있지만 빌트인. py-spy (third-party) 가 sample 기반 + 거의 0 오버헤드.
timeit — micro 벤치마크
timeit.timeit("expression", number=1_000_000) 가 식 반복 시간. timeit 이 GC 와 best-of-N 처리. "이 컴프리헨션이 저 for-loop 보다 빠른가?" 질문에 유용. 주의 — micro 벤치마크가 실세계 성능에 거짓말, 캐시 동작 / 진짜 워크로드 / amortized 비용 반영 X.
메모리 profiling
tracemalloc 가 빌트인 — 할당 추적 시작, 스냅샷, file/line 별 top 할당 표시. memray (Bloomberg) 가 flame graph UI 가진 더 풍부한 외부 도구. 가끔 "왜 이게 8GB 사용?" 엔 tracemalloc 충분, production 메모리 profiling 엔 memray.