cProfile과 line_profiler로 프로파일링
cProfile과 줄 단위 프로파일링으로 CPU 병목 지점을 찾습니다.
cProfile과 line_profiler로 프로파일링은(는) CoddyKit의 무료 Python Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Python Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Python Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
프로파일링이 필요한 이유
프로파일링은 어떤 함수가 가장 많은 시간을 소비하는지 파악하여 최적화 작업의 방향을 제시합니다. 최적화하기 전에 항상 프로파일링하십시오. 절대 추측하지 마십시오.
import cProfile
def slow():
total = 0
for i in range(1_000_000):
total += i
return total
cProfile.run("slow()")CLI에서 cProfile 실행
스크립트를 수정하지 않고 전체 스크립트를 프로파일링합니다: python -m cProfile -s cumtime script.py. cumtime, tottime 또는 calls를 기준으로 정렬할 수 있습니다.
# python -m cProfile -s cumtime my_script.py
#
# ncalls tottime percall cumtime percall filename:lineno(function)
# 1000 0.500 0.001 2.100 0.002 utils.py:10(process)코드에서 cProfile 사용
cProfile.Profile을 만들고 활성화하거나 비활성화한 다음, pstats로 통계를 출력합니다.
import cProfile, pstats, io
pr = cProfile.Profile()
pr.enable()
# ... code to profile ...
pr.disable()
stream = io.StringIO()
ps = pstats.Stats(pr, stream=stream).sort_stats("cumulative")
ps.print_stats(10) # top 10
print(stream.getvalue())pstats 필터링
print_stats(pattern)을 사용하여 특정 모듈이나 함수 이름 패턴에 해당하는 프로파일러 출력만 필터링합니다.
import cProfile, pstats
cProfile.run("my_function()", "profile.out")
stats = pstats.Stats("profile.out")
stats.sort_stats("tottime")
stats.print_stats("mymodule") # only mymodule functionsline_profiler
line_profiler는 함수별 시간만이 아니라 줄별 실행 시간도 보여 줍니다. 따라서 함수 내부에서 가장 오래 걸리는 줄을 찾는 데 필수적입니다.
# pip install line_profiler
# Decorate target function:
from line_profiler import profile
@profile
def process(data):
result = []
for item in data: # <- which line is slow?
result.append(item*2)
return result
# Run: kernprof -l -v script.pykernprof CLI
kernprof -l script.py는 줄 프로파일링을 활성화한 상태로 스크립트를 실행하며, -v를 사용하면 보고서를 즉시 표시합니다.
# kernprof -l -v script.py
#
# Line # Hits Time Per Hit % Time Line Contents
# ======================================================
# 4 1 2.0 2.0 1.0 result = []
# 5 1000 120.0 0.1 60.0 for item in data:
# 6 1000 80.0 0.1 39.0 result.append(item*2)Jupyter에서 프로파일링
Jupyter는 %prun(cProfile) 및 %lprun(line_profiler) 매직 명령을 제공합니다.
# In a Jupyter cell:
# %prun -s cumulative my_function(data)
# %load_ext line_profiler
# %lprun -f my_function my_function(data)병목 지점 식별
누적 시간이 가장 높은 함수(전체 호출 흐름)와 총 시간이 가장 높은 함수(호출된 함수의 시간은 제외하고 해당 함수 자체에 걸린 시간)에 집중합니다.
# cumtime = total time including callees (find root cause)
# tottime = time in function itself (find where work happens)
#
# Optimise the function with highest tottime first성급한 최적화 피하기
먼저 프로파일링한 다음 측정된 병목을 최적화합니다. 일반적인 Python 속도 향상 방법으로는 내장 기능 사용, 반복문을 NumPy 연산으로 옮기기, 반복 조회 캐시하기, ctypes/cffi를 통해 C 호출하기 등이 있습니다.
# Before optimising:
# profile shows: process_row() 95% of time
# Speedup: vectorise with NumPy
import numpy as np
arr = np.array(data)
result = arr * 2 # 100x faster than Python looppy-spy: 샘플링 프로파일러
py-spy는 코드를 수정하지 않고 실행 중인 프로세스를 프로파일링합니다. 실행 중인 PID에 연결할 수 있습니다.
# pip install py-spy
# Profile for 30 s and show flamegraph:
# py-spy top --pid 12345
# py-spy record -o profile.svg --pid 12345 --duration 30timeit으로 벤치마킹
특정 표현식의 미시 벤치마크에는 timeit을 사용합니다.
import timeit
result = timeit.timeit(
"[x*2 for x in range(1000)]",
number=10_000
)
print(f"{result:.3f} s for 10k runs")빠른 확인
cProfile 보고서에서 tottime은 무엇을 보여 주나요?
복습
느린 함수를 찾으려면 cProfile을 사용하고, 느린 줄을 찾으려면 line_profiler를 사용합니다. 근본 원인을 찾으려면 -s cumtime으로 프로파일링합니다. 입증된 병목만 최적화하고, 가장 큰 효과를 얻으려면 NumPy 벡터화, 캐싱 또는 C 확장을 사용합니다.
자주 묻는 질문
“cProfile과 line_profiler로 프로파일링” 강의는 무료인가요?
네 — “cProfile과 line_profiler로 프로파일링” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Python Academy 강의 전체를 잠금 해제할 수 있습니다. Python Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“cProfile과 line_profiler로 프로파일링”에서 뭘 배우나요?
cProfile과 줄 단위 프로파일링으로 CPU 병목 지점을 찾습니다. 브라우저에서 직접 실행하는 실습 코드로 Python Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Python Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Python Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“cProfile과 line_profiler로 프로파일링” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Python Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Python Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- CPython 참조 횟수 계산
- 가비지 수집기와 순환 참조
- cProfile과 line_profiler로 프로파일링
- tracemalloc으로 메모리 프로파일링