【发布时间】:2020-04-28 13:02:36
【问题描述】:
这是我定义定时装饰器的代码:
from functools import wraps, lru_cache
def timed(fn):
from time import perf_counter
@wraps(fn)
def inner(*args,**kwargs):
start = perf_counter()
result = fn(*args,**kwargs)
end = perf_counter()
timer = end - start
fs = '{} took {:.3f} microseconds'
print(fs.format(fn.__name__, (end - start) * 1000000))
return result
return inner
这里是函数定义:
@timed
@lru_cache
def factorial(n):
result = 1
cache = dict()
if n < 2:
print('Calculating factorial for n > 1')
result = 1
print(f'factorial of {result} is {result}')
else:
for i in range(1,n+1):
if i in cache.items():
result = cache[i]
#print(f'factorial of {i} is {result}')
else:
result *= i
cache[i] = result
print(f'factorial of {i} is {result}')
#print(f'{cache}')
return result
以下是对函数的调用:
阶乘(3)
阶乘(10)
阶乘(10)
这是输出
factorial of 3 is 6
factorial took 32.968 microseconds
factorial of 10 is 3628800
factorial took 11.371 microseconds
**factorial took 0.323 microseconds**
问题: 为什么我第二次调用 factorial(10) 时没有打印出来?
【问题讨论】:
-
你为什么使用
lru_cache和维护你自己的缓存? -
我应该把它拿出来吗?
标签: python-3.x python-decorators