메모리 사용량 코드 프로파일링

효율적인 Python 코드 작성

Logan Thomas

Scientific Software Technical Trainer, Enthought

간단한 방법

import sys
nums_list = [*range(1000)]
sys.getsizeof(nums_list)
9112
import numpy as np

nums_np = np.array(range(1000))
sys.getsizeof(nums_np)
8096
효율적인 Python 코드 작성

코드 프로파일링: 메모리

  • 메모리 소비에 대한 상세 통계
  • 줄 단위 분석
  • 사용 패키지: memory_profiler
pip install memory_profiler
  • memory_profiler 패키지 사용
%load_ext memory_profiler

%mprun -f convert_units convert_units(heroes, hts, wts)
효율적인 Python 코드 작성

코드 프로파일링: 메모리

  • memory_profiler 사용 시 함수를 임포트해야 합니다
    • hero_funcs.py

 

from hero_funcs import convert_units
%load_ext memory_profiler

%mprun -f convert_units convert_units(heroes, hts, wts)
효율적인 Python 코드 작성

%mprun 출력

%mprun -f convert_units convert_units(heroes, hts, wts)

alt="mprun 매직 커맨드의 메모리 사용량 프로파일링 통계 표 출력"

효율적인 Python 코드 작성

%mprun 출력

%mprun -f convert_units convert_units(heroes, hts, wts)

alt="Line # 열이 강조된 mprun 매직 커맨드의 메모리 사용량 프로파일링 통계 표 출력"

효율적인 Python 코드 작성

%mprun 출력

%mprun -f convert_units convert_units(heroes, hts, wts)

alt="Mem usage 열이 강조된 mprun 매직 커맨드의 메모리 사용량 프로파일링 통계 표 출력"

효율적인 Python 코드 작성

%mprun 출력

%mprun -f convert_units convert_units(heroes, hts, wts)

alt="Increment 열이 강조된 mprun 매직 커맨드의 메모리 사용량 프로파일링 통계 표 출력"

효율적인 Python 코드 작성

%mprun 출력

%mprun -f convert_units convert_units(heroes, hts, wts)

alt="Line contents 열이 강조된 mprun 매직 커맨드의 메모리 사용량 프로파일링 통계 표 출력"

효율적인 Python 코드 작성

%mprun 출력

%mprun -f convert_units convert_units(heroes, hts, wts)

alt="mprun 매직 커맨드의 메모리 사용량 프로파일링 통계 표 출력"

효율적인 Python 코드 작성

%mprun 출력 시 주의사항

%mprun -f convert_units convert_units(heroes, hts, wts)

alt="출력에서 메비바이트(MiB)가 강조된 mprun 매직 커맨드의 메모리 사용량 프로파일링 통계 표 출력"

효율적인 Python 코드 작성

%mprun 출력 시 주의사항

이 예제에서는 35,000개의 히어로를 무작위로 샘플링한 데이터를 사용합니다.

(원본 480개 슈퍼히어로 데이터셋이 아님)

%mprun -f convert_units convert_units(heroes, hts, wts)

alt="mprun 매직 커맨드의 메모리 사용량 프로파일링 통계 표 출력"

효율적인 Python 코드 작성

%mprun 출력 시 주의사항

메모리 할당량이 작으면 0.0 MiB로 출력될 수 있습니다.

(원본 480개 슈퍼히어로 데이터셋 사용)

%mprun -f convert_units convert_units(heroes, hts, wts)

alt="Increment 열의 모든 행이 0.0 MiB로 표시된 mprun 매직 커맨드의 메모리 사용량 프로파일링 통계 표 출력"

효율적인 Python 코드 작성

%mprun 출력 시 주의사항

  • 운영 체제를 조회하여 메모리를 검사합니다
  • 플랫폼 및 실행 환경에 따라 결과가 다를 수 있습니다
    • 메모리 소비량을 기준으로 각 코드 줄을 비교하는 것은 여전히 가능합니다
효율적인 Python 코드 작성

연습해 봅시다!

효율적인 Python 코드 작성

Preparing Video For Download...