装饰器做缓存

Posted AmilyAmily

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了装饰器做缓存相关的知识,希望对你有一定的参考价值。

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

以上是关于装饰器做缓存的主要内容,如果未能解决你的问题,请参考以下文章

用装饰器做一个登陆系统

用装饰器做一个登陆功能(进阶):

python装饰器

python装饰器使用

Python 装饰器初探

Python 元类与类装饰器