爱上python系列------python性能(七):lru_cache为函数计算加速

缓存在计算的时候可以避免重复计算,现在的数据库很多也提供缓存技术,比如redis

python的functools 模块就提供了一个工具,可以使用装饰器进行给函数进行缓存(LRU),重复的参数的就不进行重复计算了

下面做一个实验

1.不使用缓存

import functools
import math
import numpy as np
import time

ls=[int(np.random.rand()*100) for i in range(1000000)]
#@functools.lru_cache(maxsize=100)
def memoized_sin(x):
    return math.sin(math.sin(math.sin(math.sin(math.sin(math.sin(x))))))
start=time.time()
for i in ls:
	memoized_sin(i)
print(time.time()-start)
#print(memoized_sin.cache_info())

结果:

1.314882755279541

2.使用缓存:

import functools
import math
import numpy as np
import time

ls=[int(np.random.rand()*100) for i in range(1000000)]
@functools.lru_cache(maxsize=100)
def memoized_sin(x):
    return math.sin(math.sin(math.sin(math.sin(math.sin(math.sin(x))))))
start=time.time()
for i in ls:
	memoized_sin(i)
print(time.time()-start)
#print(memoized_sin.cache_info())

结果:

0.22953534126281738

差距还是蛮大的,如果函数计算越复杂,那么就越节省时间

猜你喜欢

转载自blog.csdn.net/zhou_438/article/details/109273513
今日推荐