You can use decorator to add processing before and after executing a function.
Once you have defined the decorator function, you can add processing just by writing @function name before the function you want to decorate, which is convenient when you want to write a lot of partially different functions or add a little processing.
Below, we define the decorator function check_execution_time (), which measures the execution time of a function, and decorate the appropriate function test ().
python
import time
def check_execution_time(func): #func is a decorate target
def wrapper(*args, **kwargs): #The argument to the decorate target goes here
time1 = time.time() #Time before execution
res = func(*args, **kwargs) #Execute the function received here
time2 = time.time() #Time after execution
erapsed_time = time2 - time1 #Calculate execution time
return res, erapsed_time #Returns the execution result
return wrapper
@check_execution_time #set decorator
def test(n): #Functions to be decorated
sum_n = 0
for k in range(n):
sum_n += k
return sum_n
sum_n, erapsed_time = test(1000000)
print('sum_k: %d' % sum_n)
print('erapsed_time: %1.3f' % erapsed_time)
output
sum_k: 499999500000
erapsed_time: 0.052
Let's try!
Recommended Posts