Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- nvidia-smi
- ubuntu
- 기타 연주
- pip
- error
- label
- Visual Studio
- 컨테이너
- mysql
- windows forms
- pandas
- pytorch
- Linux
- paramiko
- SSH
- VS Code
- C++
- OpenCV
- 채보
- YOLO
- 오류
- Docker
- Numpy
- 프로그래머스
- Selenium
- C#
- Python
- 핑거스타일
- C
- JSON
Archives
- Today
- Total
기계는 거짓말하지 않는다
Python tracemalloc 모듈 메모리 할당 추적 본문
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
'Python' 카테고리의 다른 글
Python faulthandler 모듈 Segmentation Fault 진단 (0) | 2025.01.25 |
---|---|
Python colorsys 모듈을 이용한 일정한 분포의 색상 생성 함수 (0) | 2025.01.21 |
Python configparser config file 주석(comment) 유지 (0) | 2025.01.21 |
Python open 함수 파일 모드(mode) (3) | 2024.09.03 |
Python paramiko 프롬프트 상호작용 invoke_shell (0) | 2024.08.20 |
Comments