반응형



파이썬에서 코드 실행시간을 측정하는 방법을 찾아 테스트해보았습니다.



파이썬 3.3+ 이상부터 perf_counter와 process_time를 사용할 수 있는데  차이점은 다음과 같습니다. 


perf_counter는 sleep 함수를 호출하여 대기한  시간을 포함하여 측정합니다. 

process_time는 실제로 연산하는데 걸린 시간만 측정합니다. 


import time


def process1():
    start = time.perf_counter()
    time.sleep(1)
    return (time.perf_counter()-start)

def process2():
    start = time.process_time()
    time.sleep(1)
    return (time.process_time()-start)


print('use perf_counter :', process1(), 'sec')
print('use process_time :', process2(), 'sec')



실행 결과 process_time는 sleep을 호출하여 1초 대기한 시간을 포함시키지 않은 걸 알 수있습니다. 

process_time의 경우 0에 아주 가까운 수로 출력되기도 합니다. 



use perf_counter : 1.0139003 sec

use process_time : 0.0 sec





perf_counter와 process_time를 사용하여 파이를 계산해주는 코드를 측정해보았습니다.


import time


# https://github.com/MrBlaise/learnpython/blob/master/Numbers/pi.py
def calcPi(limit):  # Generator function
    """
    Prints out the digits of PI
    until it reaches the given limit
    """

    q, r, t, k, n, l = 1, 0, 1, 1, 3, 3

    decimal = limit
    counter = 0

    while counter != decimal + 1:
            if 4 * q + r - t < n * t:
                    # yield digit
                    yield n
                    # insert period after first digit
                    if counter == 0:
                            yield '.'
                    # end
                    if decimal == counter:
                            print('')
                            break
                    counter += 1
                    nr = 10 * (r - n * t)
                    n = ((10 * (3 * q + r)) // t) - 10 * n
                    q *= 10
                    r = nr
            else:
                    nr = (2 * q + r) * l
                    nn = (q * (7 * k) + 2 + (r * l)) // (t * l)
                    q *= k
                    t *= l
                    l += 2
                    k += 1
                    n = nn
                    r = nr


start = time.perf_counter()
calcPi(1000)
end = time.perf_counter()
print('perf_counter:', end-start, 'seconds')

start = time.process_time()
calcPi(1000)
end = time.process_time()
print('process_time:', end-start, 'seconds')



실행시켜보았더니 이상하게도 process_time를 사용한 경우 0초로 나옵니다. 



perf_counter: 5.299999999999749e-06 seconds

process_time: 0.0 seconds




우분투와 몇가지 온라인 파이썬으로 실행해보니 다음처럼 process_time도 출력됩니다.  

윈도우에서만 제대로 출력안되는 이유를 모르겠네요.



perf_counter: 1.8900027498602867e-06 seconds                                                                                                                                       

process_time: 2.5000000000025002e-06 seconds  





참고로 timeit을 사용하는 경우입니다. 


import timeit


# https://github.com/MrBlaise/learnpython/blob/master/Numbers/pi.py
def calcPi(limit):  # Generator function
    """
    Prints out the digits of PI
    until it reaches the given limit
    """

    q, r, t, k, n, l = 1, 0, 1, 1, 3, 3

    decimal = limit
    counter = 0

    while counter != decimal + 1:
            if 4 * q + r - t < n * t:
                    # yield digit
                    yield n
                    # insert period after first digit
                    if counter == 0:
                            yield '.'
                    # end
                    if decimal == counter:
                            print('')
                            break
                    counter += 1
                    nr = 10 * (r - n * t)
                    n = ((10 * (3 * q + r)) // t) - 10 * n
                    q *= 10
                    r = nr
            else:
                    nr = (2 * q + r) * l
                    nn = (q * (7 * k) + 2 + (r * l)) // (t * l)
                    q *= k
                    t *= l
                    l += 2
                    k += 1
                    n = nn
                    r = nr


print(timeit.timeit("calcPi(1000)", setup="from __main__ import calcPi"))





참고 


https://stackoverflow.com/a/52228375





문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts