Python common operations
Class decorator
Timer
To count the running time of each function, you can design a class decorator as a timer, and then declare it directly in front of the function each time it is used.
The following are general timers. Just declare @timer in front of the function when using it.
# This is for timing
def timer(func):
def func_wrapper(*args,**kwargs):
from time import time
time_start = time()
result = func(*args,**kwargs)
time_end = time()
time_spend = time_end - time_start
print('\n{0} cost time {1} s\n'.format(func.__name__, time_spend))
return result
return func_wrapper
Write @timer directly above the function definition when using it
@timer
def test():
print("hello world!")