1. 학습
  2. /
  3. 강의
  4. /
  5. 효율적인 Python 코드 작성

Connected

연습 문제

%mprun 사용하기: Hero BMI 2.0

다른 방식으로 BMI를 계산하면 메모리를 아낄 수 있는지 살펴보세요. 기억하신다면, 각 히어로의 키와 몸무게는 numpy 배열에 저장되어 있어요. 즉, NumPy의 편리한 배열 인덱싱과 브로드캐스팅을 사용해 계산할 수 있다는 뜻이죠. calc_bmi_arrays라는 함수가 만들어져 bmi_arrays.py 파일에 저장되어 있으며, 편의를 위해 아래에 표시했어요:

def calc_bmi_arrays(sample_indices, hts, wts):

    # Gather sample heights and weights as arrays
    s_hts = hts[sample_indices]
    s_wts = wts[sample_indices]

    # Convert heights from cm to m and square with broadcasting
    s_hts_m_sqr = (s_hts / 100) ** 2

    # Calculate BMIs as an array using broadcasting
    bmis = s_wts / s_hts_m_sqr

    return bmis

이 함수는 필요한 모든 계산을 배열을 사용해 수행한다는 점에 주목하세요.

이 업데이트된 배열 접근 방식이 메모리 사용량을 줄이는지 확인해 봅시다:

  • IPython 세션에 memory_profiler 패키지를 로드하세요.
  • bmi_arrays에서 calc_bmi_arrays를 가져오세요.
  • 위 단계를 완료한 뒤, %mprun을 사용해 슈퍼히어로 데이터에 대해 동작하는 calc_bmi_arrays() 함수를 프로파일링하세요. sample_indices 배열, hts 배열, wts 배열은 세션에 로드되어 있어요.

코딩을 마친 후, 다음 질문에 답하세요:

calc_bmi_array() 함수에서 배열 인덱싱과 브로드캐스팅 코드 줄은 얼마나 많은 메모리를 사용하나요? (즉, 이 네 줄 코드에 대한 Increment 열의 합계는 얼마인가요?)

지침

50 XP

가능한 답변