We implement timers in two ways .
import time
def timer_dec(func):
def inner(*args, **kwargs):
start = time.time()
ret_val = func(*args, **kwargs)
end = time.time()
print(f'pay time is {end-start} s')
return ret_val
return inner
@timer_dec
def haha():
print(' drowned in laughter. ')
time.sleep(0.01)
haha()
Output results
drowned in laughter.
pay time is 0.010136842727661133 s
Use the generator to realize , Need help Python Built in Library contextlib help .
It doesn't mean that we have to resort to contextlib, It's about using contextlib Can be more elegant
You can refer to : Shallow python in with Usage of , Context manager
from contextlib import contextmanager
def haha():
print(' drowned in laughter. ')
time.sleep(0.01)
@contextmanager
def timer_gen():
start = time.time()
yield
end = time.time()
print(f'pay time is {end-start} s')
with timer_gen():
haha()
Output results
drowned in laughter.
pay time is 0.010103464126586914 s