실행 시간 살펴보기

효율적인 Python 코드 작성

Logan Thomas

Scientific Software Technical Trainer, Enthought

왜 코드를 측정해야 할까요?

  • 최적의 코딩 방식을 선택할 수 있음
  • 더 빠른 코드는 더 효율적임
효율적인 Python 코드 작성

코드는 어떻게 측정하나요?

  • IPython 매직 명령 %timeit으로 실행 시간 계산

  • 매직 명령: 표준 Python 문법을 보강하는 기능

    • "%"로 시작
    • 문서 링크 (here)
    • %lsmagic로 사용 가능한 명령 확인
효율적인 Python 코드 작성

%timeit 사용

측정할 코드

import numpy as np

rand_nums = np.random.rand(1000)

%timeit으로 측정

%timeit rand_nums = np.random.rand(1000)
8.61 µs ± 69.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
효율적인 Python 코드 작성

%timeit 출력

alt="Magic 명령 timeit 출력"

효율적인 Python 코드 작성

%timeit 출력

alt="평균과 표준편차가 강조된 Magic 명령 timeit 출력"

효율적인 Python 코드 작성

%timeit 출력

alt="실행 횟수와 루프 수가 강조된 Magic 명령 timeit 출력"

효율적인 Python 코드 작성

실행/루프 수 지정

실행 횟수(-r) 및/또는 루프 수(-n) 설정

# 실행 횟수를 2로 설정 (-r2)
# 루프 수를 10으로 설정 (-n10)

%timeit -r2 -n10 rand_nums = np.random.rand(1000)
16.9 µs ± 5.14 µs per loop (mean ± std. dev. of 2 runs, 10 loops each)
효율적인 Python 코드 작성

라인 매직 모드에서 %timeit 사용

라인 매직(%timeit)

# 한 줄 코드

%timeit nums = [x for x in range(10)]
914 ns ± 7.33 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
효율적인 Python 코드 작성

셀 매직 모드에서 %timeit 사용

셀 매직(%%timeit)

# 여러 줄 코드

%%timeit
nums = []
for x in range(10):
    nums.append(x)
1.17 µs ± 3.26 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
효율적인 Python 코드 작성

출력 저장

출력을 변수에 저장(-o)

times = %timeit -o rand_nums = np.random.rand(1000)
8.69 µs ± 91.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
효율적인 Python 코드 작성
times.timings
[8.697893059998023e-06,
 8.651204760008113e-06,
 8.634270530001232e-06,
 8.66847825998775e-06,
 8.619398139999247e-06,
 8.902550710008654e-06,
 8.633500570012985e-06]
times.best
8.619398139999247e-06
times.worst
8.902550710008654e-06
효율적인 Python 코드 작성

시간 비교

Python 자료 구조는 정식 이름으로 생성할 수 있습니다

formal_list = list()
formal_dict = dict()
formal_tuple = tuple()

Python 자료 구조는 리터럴 문법으로도 생성할 수 있습니다

literal_list = []
literal_dict = {}
literal_tuple = ()
효율적인 Python 코드 작성
f_time = %timeit -o formal_dict = dict()
145 ns ± 1.5 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
l_time = %timeit -o literal_dict = {}
93.3 ns ± 1.88 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
diff = (f_time.average - l_time.average) * (10**9)
print('l_time better than f_time by {} ns'.format(diff))
l_time better than f_time by 51.90819192857814 ns
효율적인 Python 코드 작성

시간 비교

%timeit formal_dict = dict()
145 ns ± 1.5 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%timeit literal_dict = {}
93.3 ns ± 1.88 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
효율적인 Python 코드 작성

준비 완료!

효율적인 Python 코드 작성

Preparing Video For Download...