Skip to content

Instantly share code, notes, and snippets.

@selfboot
Created August 10, 2014 10:01
Show Gist options
  • Save selfboot/99f59f1b4cf8fb8c08eb to your computer and use it in GitHub Desktop.
Save selfboot/99f59f1b4cf8fb8c08eb to your computer and use it in GitHub Desktop.
用装饰器实现缓存机制,避免斐波那契数列递归实现中的重复调用,然后比较存在缓存和没有缓存下的运行时间。
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from functools import wraps
def fib_direct(n):
assert n > 0, 'invalid n'
if n < 3:
return n
else:
return fib_direct(n - 1) + fib_direct(n - 2)
def cache(func):
caches = {}
@wraps(func)
def wrap(*args):
if args not in caches:
caches[args] = func(*args)
return caches[args]
return wrap
@cache
def fib_cache(n):
assert n > 0, 'invalid n'
if n < 3:
return 1
else:
return fib_cache(n - 1) + fib_cache(n - 2)
if __name__ == "__main__":
from timeit import Timer
t1 = Timer("fib_direct(10)", "from __main__ import fib_direct")
t2 = Timer("fib_cache(10)", "from __main__ import fib_cache")
print t1.timeit(100000)
print t2.timeit(100000)
"""
1.71311998367
0.0279998779297
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment