1. सीखें
  2. /
  3. पाठ्यक्रम
  4. /
  5. 효율적인 Python 코드 작성

Connected

अभ्यास

%lprun 사용하기: 병목 구간 수정

이전 연습 문제에서 convert_units() 함수를 프로파일링해 보니, new_hts 리스트 컴프리헨션이 잠재적인 병목일 수 있음을 확인하셨죠. new_wts 리스트 컴프리헨션도 실행 시간에서 비슷한 비율을 차지했다는 점을 눈치채셨나요? 이는 new_hts와 new_wts 객체를 다른 방식으로 만드는 편이 좋다는 신호입니다.

각 히어로의 키와 몸무게는 numpy 배열에 저장되어 있으므로, 리스트 컴프리헨션 대신 배열 브로드캐스팅을 사용해 단위를 변환할 수 있습니다. 아래 함수에 그렇게 구현해 두었습니다:

def convert_units_broadcast(heroes, heights, weights):

    # Array broadcasting instead of list comprehension
    new_hts = heights * 0.39370
    new_wts = weights * 2.20462

    hero_data = {}

    for i,hero in enumerate(heroes):
        hero_data[hero] = (new_hts[i], new_wts[i])

    return hero_data

line_profiler 패키지를 IPython 세션에 로드하세요. 그런 다음 %lprun을 사용해 슈퍼히어로 데이터에 대해 convert_units_broadcast() 함수를 프로파일링해 보세요. convert_units_broadcast() 함수, heroes 리스트, hts 배열, wts 배열은 이미 세션에 로드되어 있습니다. 코드를 실행한 뒤 아래 질문에 답해 주세요:

convert_units_broadcast() 함수 전체 실행 시간 대비, new_hts 배열 브로드캐스팅 코드 줄에서 소요된 시간의 비율은 얼마인가요?

निर्देश

50 XP

संभावित उत्तर