0

有没有办法让它工作?

func=i_want_it_to_cache_everything(lambda a,b:a+b)

必须在一行中完成......

更新2:

我想出了解决方案(感谢所有回复的人!)。但是……有一个有趣的现象:缓存减慢程序?

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)
4

1 回答 1

2
>>> from functools import lru_cache
>>> x = lru_cache()(lambda a,b:a+b)
>>> x(2,3)
5
>>> x(4,2)
6
>>> x(2,3)
5
>>> x.cache_info()
CacheInfo(hits=1, misses=2, maxsize=100, currsize=2)
于 2012-04-22T17:55:44.400 回答