python time module surprising results

Viewed 31

I just read about the lru_cache decorator and ran the below experiment.

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)

The results surprised me:

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

However, once I measure the cached and non cached functions one at a time by keeping only one of the functions, I get:

not cached: 4.3182690143585205
cached: 0.00010395050048828125

The latter result for cached makes more sense to me as it's significantly faster. The difference between two results for cached is so drastic - Do you have any intuition as to what I'm doing wrong?

Thank you!

1 Answers

You made a very simple mistake - fib with cache internally calls fib without cache.

Try

@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)
Related