Python 파이썬 함수 실행 시간측정
- 목적 : 함수 실행 속도를 확인하여 프로그램의 성능을 파악하기 위함
* 사전 지식
- A 클래스의 b 함수의
__name__값은 b이고, __qualname__값은 A.b이다. (python 3.3부터)
time.perf_counter : 코드 연산시간 외에 sleep, file io 등 pending에 들어가는 시간까지 포함하여 측정. 즉, 프로그램 전체의 실행시간 측정
time.process_time : 실제 연산(처리)된 시간만 측정
- print시,
flush=True : print()함수는 효율성을 높이기 위해 데이터를 버퍼링하지 않고 각 호출에서 계속 플러시함.
@wraps(func) 과 decorator 에 대하여 ([참조]Decorator 사용하기 )
* decorator 활용한 시간 측정
1. 시간 측정 데코레이터(@how_long) 만들기
from functools import wraps
import time
def how_long(func):
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.perf_counter()
result = func(*args, **kwargs)
end_time = time.perf_counter()
total_time = end_time - start_time
print(f"{func.__qualname__}: {total_time} 초", flush=True)
return result
return wrapper
2. 시간 측정하고자하는 함수에 데코레이션 적용
class ClassTest:
def __init__(self):
self.result = 0
@how_long
def add(self, a, b):
return self.result + a + b
3. 결과 확인
a = ClassTest()
a.add(1,2)
ClassTest.add: 3.769004251807928e-06 초
3