python 计算函数执行时间装饰器(带参数装饰器写法)

import time
import functools
DEFAULT_FMT = '[{elapsed:0.8f}s] {name}({args}) -> {result}'
def clock(fmt=DEFAULT_FMT): # <1>
def decorate(func): # <2>
@functools.wraps(func)
def clocked(*args, *kwargs):
t0 = time.time()
result = func(
args, **kwargs)
elapsed = time.time() - t0
name = func.name
arg_lst = []
if args:
arg_lst.append(', '.join(repr(arg) for arg in args))
if kwargs:
pairs = ['%s=%r' % (k, w) for k, w in sorted(kwargs.items())]
arg_lst.append(', '.join(pairs))
arg_str = ', '.join(arg_lst)
print('[%0.8fs] %s(%s) -> %r ' % (elapsed, name, arg_str, result))
return result
return clocked
return decorate

@functools.lru_cache() # ➊
@clock() # ➋
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-2) + fibonacci(n-1)
if name=='main':
print(fibonacci(6))

你可能感兴趣的:(python 计算函数执行时间装饰器(带参数装饰器写法))