それを機能させる方法はありますか?
func=i_want_it_to_cache_everything(lambda a,b:a+b)
そしてそれは一行で行われなければなりません...
Update2:
私は解決策を見つけました(返信してくれたすべての人に感謝します!)。しかし...興味深い現象があります:キャッシュはプログラムを遅くしますか?
import functools,datetime,timeit
@functools.lru_cache(maxsize=50000)
def euclidean_distance3(p1,p2):
return (p1[0]-p2[0])**2+(p1[1]-p2[1])**2+(p1[2]-p2[2])**2+(p1[3]-p2[3])**2
euclidean_distance=(functools.lru_cache(maxsize=50000)(lambda p1,p2: (p1[0]-p2[0])**2+(p1[1]-p2[1])**2+(p1[2]-p2[2])**2+(p1[3]-p2[3])**2))
euclidean_distance2=lambda p1,p2: (p1[0]-p2[0])**2+(p1[1]-p2[1])**2+(p1[2]-p2[2])**2+(p1[3]-p2[3])**2
print(datetime.datetime.now())
def test1():
for z in range(50):
for i in range(200):
for j in range(200):
euclidean_distance((i,i,i,i),(j,j,j,j));
def test2():
for z in range(50):
for i in range(200):
for j in range(200):
euclidean_distance2((i,i,i,i),(j,j,j,j));
def test3():
for z in range(50):
for i in range(200):
for j in range(200):
euclidean_distance3((i,i,i,i),(j,j,j,j));
t1=timeit.Timer(test1)
print(t1.timeit(1))
t2=timeit.Timer(test2)
print(t2.timeit(1))
t3=timeit.Timer(test3)
print(t3.timeit(1))
print(euclidean_distance.cache_info())
print(euclidean_distance3.cache_info())
出力:
9.989034592910151
4.936129879313011
10.528836308312947
CacheInfo(hits=1960000, misses=40000, maxsize=50000, currsize=40000)
CacheInfo(hits=1960000, misses=40000, maxsize=50000, currsize=40000)