import time defdecorate_add(x, y): start = time.time() defadd(x, y): return x + y result = add(x, y) end = time.time() time_consumption = end - start print(result, time_consumption)
import time defdecorater(func): defwrapped(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print('time: ', end - start) return result return wrapped
import time defdecorater(func): defwrapped(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print('time: ', end - start) return result return wrapped
@decorater defadd(x, y): return x + y
add(1, 2)
输出还是老样子:
0.0
3
看来@只是一个简写。
再进一步
其实到此为止已经足够了。但是既然官方都有,那我们就用一下吧。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
import time from functools import wraps deftime_consume(f): @wraps(f) defwrapTheFunction(*args, **kargs): start = time.time() result = f(*args, **kargs) end = time.time() print(end - start) return result return wrapTheFunction @time_consume defadd(x, y): return x + y