Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

NISSO

[Python] 코드 실행 시간 측정 본문

Python

[Python] 코드 실행 시간 측정

oniss 2021. 11. 26. 11:15

코드를 짜고 프로그램을 실행할 때, 전체나 일부 코드의 실행 시간을 알아야 할 때가 있다.

이럴 때, time과 datetime 라이브러리를 사용하여 쉽게 시간을 측정하고 출력할 수 있다.

 

원리는 간단하다.

time.time()은 현재 시간을 계산해주는데, 각 코드를 실행하기 전후의 시간을 변수에 저장해놓고 빼주면 된다.

# 코드1

import time
import datetime

start = time.time()
y = function1(X)  # 실행할 코드
end = time.time()

sec = (end - start)
result_list = str(datetime.timedelta(seconds=sec)).split(".")
print(result_list[0])

함수 function1이 있다고 할 때, 그 함수의 실행 시간을 계산해서 print하는 코드다.

결과는 이렇게 나온다.

시,분,초 단위로, 위는 3분 27초라는 시간을 나타낸다.

# 코드2

import time
import datetime

def compute_time(start, end):
    sec = (end - start)
    result_list = str(datetime.timedelta(seconds=sec)).split(".")
    return result_list[0]


start = time.time()
y1 = function1(X)  # 실행할 코드 1
end1 = time.time()
print('finished running function1 in', compute_time(start, end1))

y2 = function2(X)  # 실행할 코드 2
end2 = time.time()
print('finished running function2 in', compute_time(end1, end2))

y3 = function3(X)  # 실행할 코드 3
end3 = time.time()
print('finished running function3 in', compute_time(end2, end3))

print('finished running all functions in total', compute_time(start, end3))

여러 코드나 함수의 실행 시간을 계산하기 위해 함수로 만들어봤다.

함수 function1,2,3이 있다고 할 때, 각각의 실행시간을 측정해서 print하고, 마지막에 전체 코드 실행 시간을 print하는 코드다.

 

'Python' 카테고리의 다른 글

[Python] os 모듈의 유용한 함수 정리  (0) 2021.12.15
[Python] sort()와 sorted() 차이  (0) 2021.06.26
[Python] 리스트로 True / False 출력  (0) 2021.06.24
Comments