PYTHON · 성능
메모리 프로파일링
메모리 사용량을 측정하고 메모리 누수를 찾는 방법입니다.
성능중급memory메모리tracemalloc__slots__
핵심 설명
메모리 사용량을 측정하고 메모리 누수를 찾는 방법입니다.
Python code
import sys
import tracemalloc
# tracemalloc으로 메모리 추적
tracemalloc.start()
# 메모리를 사용하는 작업
data = [i ** 2 for i in range(10000)]
lookup = {str(i): i for i in range(10000)}
# 현재 메모리 스냅샷
snapshot = tracemalloc.take_snapshot()
top = snapshot.statistics("lineno")
print("=== 메모리 사용 상위 항목 ===")
for stat in top[:3]:
print(f" {stat}")
# 객체 크기 측정
print(f"\n=== 객체 크기 ===")
print(f"int(1): {sys.getsizeof(1)} bytes")
print(f"str('hello'):{sys.getsizeof('hello')} bytes")
print(f"list(1000): {sys.getsizeof(list(range(1000)))} bytes")
print(f"dict(1000): {sys.getsizeof({i:i for i in range(1000)})} bytes")
print(f"tuple(1000): {sys.getsizeof(tuple(range(1000)))} bytes")
# __slots__으로 메모리 절약
class PointRegular:
def __init__(self, x, y):
self.x = x
self.y = y
class PointSlots:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
reg = PointRegular(1, 2)
slotted = PointSlots(1, 2)
print(f"\n일반: {sys.getsizeof(reg)} bytes (+ __dict__: {sys.getsizeof(reg.__dict__)})")
print(f"slots: {sys.getsizeof(slotted)} bytes")
tracemalloc.stop()학습 팁
__slots__은 인스턴스가 많은 클래스에서 메모리를 40-50% 절약합니다.
주의할 점
sys.getsizeof()는 객체의 직접 크기만 반환합니다. 중첩된 객체의 크기는 포함되지 않습니다.
자주 묻는 질문
메모리 프로파일링란 무엇인가요?
메모리 사용량을 측정하고 메모리 누수를 찾는 방법입니다.
메모리 프로파일링 학습 시 주의할 점은 무엇인가요?
sys.getsizeof() 는 객체의 직접 크기만 반환합니다. 중첩된 객체의 크기는 포함되지 않습니다.
Continue Learning
Python 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.