码迷,mamicode.com
首页 > 其他好文 > 详细

装饰器做缓存

时间:2017-05-16 16:42:15      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:print   func   *args   now()   缓存   bin   return   pytho   ==   

#!/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

装饰器做缓存

标签:print   func   *args   now()   缓存   bin   return   pytho   ==   

原文地址:http://www.cnblogs.com/AmilyWilly/p/6862069.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!