python 时间模块令人惊讶的结果

python time module surprising results

我刚刚阅读了 lru_cache 装饰器和 运行 下面的实验。

from functools import lru_cache
import time

def fib_wo_cache(n):
  return n if n < 2 else fib_wo_cache(n-1) + fib_wo_cache(n-2)

begin = time.time()
fib_wo_cache(35)
end = time.time()
print("time it took without cache: ", end-begin)


@lru_cache(maxsize=2000)
def fib_w_cache(n):
  return n if n < 2 else fib_wo_cache(n-1) + fib_wo_cache(n-2)

begin = time.time()
fib_w_cache(35)
end = time.time()
print("time it took with cache: ", end-begin)

结果让我吃惊:

time it took without cache:  4.684133052825928
time it took with cache:  4.4438371658325195

但是,一旦我通过只保留一个函数来一次测量缓存和非缓存函数,我得到:

not cached: 4.3182690143585205
cached: 0.00010395050048828125

缓存的后一个结果对我来说更有意义,因为它明显更快。缓存的两个结果之间的差异是如此之大 - 你对我做错了什么有直觉吗?

谢谢!

你犯了一个非常简单的错误 - 有缓存的 fib 在内部调用没有缓存的 fib。

尝试

@lru_cache(maxsize=2000)
def fib_w_cache(n):
  return n if n < 2 else fib_w_cache(n-1) + fib_w_cache(n-2)