使用装饰器为Python函数做缓存
2013-01-13 19:51
417 查看
写了个函数作为装饰器为Fibonacci数列做缓存,做了一下性能比较。
输出结果:
Fib without cache costs: datetime.timedelta(0, 6, 219000)
Fib with cache costs: datetime.timedelta(0, 0, 672000)
#!/usr/bin/python # coding: UTF-8 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, 6, 219000)
Fib with cache costs: datetime.timedelta(0, 0, 672000)
相关文章推荐
- python 装饰器功能以及函数参数使用
- Python 函数修饰符(装饰器)的使用
- python 使用函数装饰器的例子
- python 装饰器功能以及函数参数使用介绍
- python 装饰器功能以及函数参数使用介绍
- python 9-2 如何为被装饰的函数保存元数据,使用标准库functools中的装饰器wraps 装饰内部包裹函数
- 【转】python 装饰器功能以及函数参数使用
- python使用函数装饰器的示例,打印函数耗时
- python 函数结果缓存一段时间的装饰器
- python-函数装饰器的使用-25
- python 9-1 如何使用函数装饰器,定义函数装饰器,用来生成一个原函数基础添加新功能的函数,替代原函数
- python 函数 argparse 使用 - 针对命令行参数调用 [备忘]
- [Python学习笔记]2——Python使用函数
- python join字符连接函数的使用方法
- python基础之高阶函数、匿名函数 、装饰器,文件的读写
- Python学习笔记(七)函数的使用
- Python学习 Day 5 高阶函数 map/reduce filter sorter 返回函数 匿名函数 装饰器 偏函数
- Python模块及函数的使用
- Python过滤函数filter()使用自定义函数过滤序列实例
- Python下自定义函数的使用详解