【Python】Python装饰器缓存
18 Sep 2013- ”@”符号是Python的装饰语法。它不只用于追查,锁或日志。你可以装饰一个Python函数,记住调用结果供后续使用。这种技术被称为memoization的。
- 缓存装饰器可以将输出与计算它所需的参数放在一起,并且直接在后续的调用中返回它。
python:
#!/usr/bin/python
# coding: UTF-8
#ref:http://blog.csdn.net/caiknife/article/details/8498721
import datetime
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()
for i in range(10):
fib(30)
end = now()
print "Fib without cache costs: %r" % (end - start)
start = now()
for i in range(10):
fib_with_cache(30)
end = now()
print "Fib with cache costs: %r" % (end - start)
结果:
Fib without cache costs: datetime.timedelta(0, 4, 161000) Fib with cache costs: datetime.timedelta(0, 0, 417000)
从结果可以看出,当使用装饰器来为函数做缓存的时候,所用时间更少。
转载请注明:于哲的博客 » 【Python】Python装饰器缓存