Python中使用flask-cache的前后性能对比
用 flask 写的视频站,估计读写数据库太频繁,cpu 占用一直很高!
基本上有多少吃多少,换过 DO、linode、vultr 等 vps,各种配置都换过,基本没卵用,cpu 有多少就占用多少!
然后今天用上 flask-cache 之后,cpu、内存、硬盘 IO 等占用下降明显!
Python中使用flask-cache的前后性能对比
5 回复
请问下,这是哪家公司的主机监控页面?
Flask-Cache(现在通常用Flask-Caching)确实能显著提升性能,特别是在重复查询数据库或复杂计算场景。直接看对比代码:
from flask import Flask, jsonify
from flask_caching import Cache
import time
app = Flask(__name__)
app.config['CACHE_TYPE'] = 'simple'
cache = Cache(app)
# 模拟耗时操作
def expensive_operation():
time.sleep(2) # 模拟2秒耗时
return {'data': '计算结果', 'timestamp': time.time()}
@app.route('/no_cache')
def no_cache():
start = time.time()
result = expensive_operation()
elapsed = time.time() - start
return jsonify({'result': result, 'time': elapsed})
@app.route('/with_cache')
@cache.cached(timeout=60) # 缓存60秒
def with_cache():
start = time.time()
result = expensive_operation()
elapsed = time.time() - start
return jsonify({'result': result, 'time': elapsed})
if __name__ == '__main__':
app.run(debug=True)
性能对比:
- 首次访问
/with_cache:约2秒(和未缓存一样) - 60秒内再次访问
/with_cache:约0.001-0.01秒(直接从内存读取) - 访问
/no_cache:每次都是2秒
实际测试结果示例:
# 第一次请求(都慢)
/no_cache: 2.001s
/with_cache: 2.003s
# 60秒内第二次请求(缓存生效)
/no_cache: 2.002s # 依然慢
/with_cache: 0.005s # 快400倍
关键机制:
@cache.cached()装饰器自动缓存函数返回值- 默认使用内存缓存,生产环境可用Redis/Memcached
- 缓存键基于函数参数,不同参数分别缓存
适用场景:
- 数据库查询结果
- API响应数据
- 模板渲染结果
- 计算密集型函数
简单说就是:对于重复请求,缓存能让响应速度提升几十到几百倍。
#1 http://bt.cn
flask-cache 这个库年久失修啊,现在应该是用它的 fork flask-caching 吧。
有什么坑分享一下么

