patrickpu 最近的时间轴更新
patrickpu

patrickpu

V2EX 第 575665 号会员,加入于 2022-03-16 14:51:58 +08:00
patrickpu 最近回复了
2022-03-18 17:43:06 +08:00
回复了 182247236 创建的主题 Python Django 中 Python 多线程连接数据问题请教
性能慢主要慢在两个方面,一个是 python 的 for 循环,一个是获取 sql 查询数据。
pymysql 是纯 python 的,而 python 的 for 循环性能是很低的,低的惨不忍听,数据量不大还好,当你一次要处理+10w 数据的时候性能就很感人了,最好的方法是用 cython 把.py 转成动态链接库.so 的形式,会有明显的加速效果。
当你查询的数据量大了后,pymysql 等 python 客户端执行的结果集获取是通过游标分块获取的,也就是说查询 1w 的数据,数据库往返请求可能会有 100 次,这些请求都是串行的是透明的,优化的方向可以考虑通过多线程并发,按 id 分块读,同时指定 limit
见 pymysql 的 cursor_iter:
def cursor_iter(cursor, sentinel, col_count, itersize):
"""
Yield blocks of rows from a cursor and ensure the cursor is closed when
done.
"""
try:
for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel):
yield rows if col_count is None else [r[:col_count] for r in rows]
finally:
cursor.close()
关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3250 人在线   最高记录 6543   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 12ms · UTC 14:06 · PVG 22:06 · LAX 07:06 · JFK 10:06
Developed with CodeLauncher
♥ Do have faith in what you're doing.