有人可以解释为什么版本 1 和 2 以相同的速度执行吗?我预计版本 2、3 和 4 需要大约相同的时间。
def fib(n):
return n if n in [0, 1] else fib(n-2)+fib(n-1)
def memoize(fn):
stored_results = {}
def memoized(*args):
try:
return stored_results[args]
except KeyError:
#nothing cached
result = stored_results[args] = fn(*args)
return result
return memoized
#version 1 (unmemoized)
print timeit.timeit('fib(35)', 'from __main__ import fib', number=1)
print fib, '\n'
#version 2
memo_fib = memoize(fib)
print timeit.timeit('memo_fib(35)', 'from __main__ import memo_fib', number=1)
print memo_fib, '\n'
#version 3 (wrapped)
fib = memoize(fib)
print timeit.timeit('fib(35)', 'from __main__ import fib', number=1)
print fib, '\n'
#version 4 (w/ decoration line)
@memoize
def fib(n):
return n if n in [0, 1] else fib(n-2)+fib(n-1)
print timeit.timeit('fib(35)', 'from __main__ import fib', number=1)
结果:
version 1: 4.95815300941
<function fib at 0x102c2b320>
version 2: 4.94982290268
<function memoized at 0x102c2b410>
version 3: 0.000107049942017
<function memoized at 0x102c2b488>
version 4: 0.000118970870972