PYTHON · 성능
프로파일링 (cProfile)
cProfile로 함수별 실행 시간을 측정하여 성능 병목을 찾습니다.
성능중급cProfile프로파일링성능profiling
핵심 설명
cProfile로 함수별 실행 시간을 측정하여 성능 병목을 찾습니다.
Python code
import cProfile
import pstats
import io
def slow_function():
total = 0
for i in range(100000):
total += i ** 2
return total
def fast_function():
return sum(i ** 2 for i in range(100000))
def main():
slow_function()
fast_function()
slow_function()
# 프로파일링 실행
profiler = cProfile.Profile()
profiler.enable()
main()
profiler.disable()
# 결과 출력
stream = io.StringIO()
stats = pstats.Stats(profiler, stream=stream)
stats.sort_stats("cumulative")
stats.print_stats(10)
print(stream.getvalue()[:500])
# 데코레이터로 개별 함수 프로파일링
def profile(func):
def wrapper(*args, **kwargs):
pr = cProfile.Profile()
pr.enable()
result = func(*args, **kwargs)
pr.disable()
pr.print_stats(sort="cumulative")
return result
return wrapper
# 명령줄: python -m cProfile -s cumulative script.py
# 시각화: pip install snakeviz
# python -m cProfile -o output.prof script.py
# snakeviz output.prof
print("프로파일링 완료")학습 팁
snakeviz로 프로파일 결과를 브라우저에서 시각적으로 분석할 수 있습니다.
주의할 점
프로파일링 자체가 오버헤드를 추가합니다. 운영 환경에서는 샘플링 프로파일러(py-spy)를 사용하세요.
자주 묻는 질문
프로파일링 (cProfile)란 무엇인가요?
cProfile 로 함수별 실행 시간을 측정하여 성능 병목을 찾습니다.
프로파일링 (cProfile) 학습 시 주의할 점은 무엇인가요?
프로파일링 자체가 오버헤드를 추가합니다. 운영 환경에서는 샘플링 프로파일러( py-spy )를 사용하세요.