首页 > 代码库 > 装饰器做缓存
装饰器做缓存
#!/usr/bin/python
# coding: UTF-8
import datetime
import time
now = datetime.datetime.now
from functools import wraps
def cache(func):
caches = {}
@wraps(func)
def wrap(*args):
if args not in caches:
caches[args] = func(*args)
return caches[args]
return wrap
def fib(num):
if num < 2:
return 1
return fib(num-1) + fib(num-2)
fib_with_cache = cache(fib)
#start = now()
start=time.time()
for i in range(10):
fib(30)
#end=now()
end = time.time()
print "Fib without cache costs: %r" % (end - start)
start = time.time()
for i in range(10):
fib_with_cache(30)
end =time.time()
print "Fib with cache costs: %r" % (end - start)
==============
Fib without cache costs: 3.1489999294281006
Fib with cache costs: 0.30900001525878906
装饰器做缓存