기계는 거짓말하지 않는다

Python tracemalloc 모듈 메모리 할당 추적 본문

Python

Python tracemalloc 모듈 메모리 할당 추적

KillinTime 2025. 2. 16. 15:15

Python의 tracemalloc은 코드에서 메모리 할당을 추적할 수 있도록 도와주는 기본 모듈이다.

가장 많은 메모리를 할당하는 5개의 파일을 표시한 출력 형식은 아래와 비슷하다.

/home/user/test.py:1817: size=18.2 MiB, count=556, average=33.5 KiB
<frozen importlib._bootstrap_external>:672: size=438 KiB, count=4584, average=98 B
/usr/lib/python3.10/threading.py:258: size=417 KiB, count=1384, average=309 B
<frozen importlib._bootstrap>:241: size=175 KiB, count=1871, average=96 B
/usr/lib/python3.10/queue.py:207: size=144 KiB, count=467, average=315 B

출력 첫 줄의 /home/user/test.py는 test.py의 1817번째 줄에서 메모리 사용량

<frozen importlib._bootstrap_external>은 모듈을 import 할 때 발생한 메모리 사용

/usr/lib/python3.10/threading.py는 thread 관련 코드에서 메모리 소비

<frozen importlib._bootstrap>은 python 내부 import 시스템에서 사용된 메모리

/usr/lib/python3.10/queue.py는 queue 관련 코드의 메모리 소비이다.

 

사용 예제는 아래와 같다.

import tracemalloc
top_k = 5
if not tracemalloc.is_tracing():
tracemalloc.start()
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics("lineno") # Code line 별 출력
for stat in top_stats[:top_k]: # Print top k
print(stat)
# stop tracing
if tracemalloc.is_tracing():
tracemalloc.stop()

메모리 차이 비교는 snapshot의 compare_to 함수로 가능하다.

import tracemalloc
top_k = 5
if not tracemalloc.is_tracing():
tracemalloc.start()
snapshot1 = tracemalloc.take_snapshot()
# other codes
# ...
# ...
snapshot2 = tracemalloc.take_snapshot()
top_stats = snapshot2.compare_to(snapshot1, 'lineno')
print(f"[ Top {top_k} differences ]")
for stat in top_stats[:top_k]:
print(stat)

더 자세한 내용은 문서를 참고하면 된다.

tracemalloc — 메모리 할당 추적 — Python 3.10.16 문서

 

tracemalloc — 메모리 할당 추적 — Python 3.10.16 문서

tracemalloc — 메모리 할당 추적 소스 코드: Lib/tracemalloc.py tracemalloc 모듈은 파이썬이 할당한 메모리 블록을 추적하는 디버그 도구입니다. 다음 정보를 제공합니다: 객체가 할당된 곳의 트레이스백

docs.python.org

 

Comments