这里的Python包装器的缓存可以避免重复计算,若存在大量重复计算的函数,则可以大幅度提高执行效率。
import math
import time
def cache(func):
cache = {}
def wrapper(*args):
if args in cache:
return cache[args]
result = func(*args)
cache[args] = result
return result
return wrapper
@cache
def expensive_func(x,y):
return math.cos(x) + (math.sqrt(abs(math.sin(x))) + math.log1p(y))**2 + (math.log(x+y**2) - math.cos(math.tan(x**2)))**2
s = time.time()*1000
for i in range(10000000):
expensive_func(1, 2)
expensive_func(3, 4)
e = time.time()*1000
print("time use : {}".format(e - s))
在expensive_func里面编写一个代价非常大的数学计算,如果不使用缓存,也就是把@cache去掉,程序将耗时20多秒。
如果直接跑该代码,可以在1.8秒内运行完成。
文章展示了如何使用Python装饰器创建一个缓存包装器,以避免重复计算,从而提高执行效率。通过一个代价高昂的数学计算函数`expensive_func`为例,比较了使用缓存和不使用缓存的性能差异,证明了缓存对于优化计算密集型任务的有效性。
3322

被折叠的 条评论
为什么被折叠?



