Python中mysql-connector在Python 3.7下运行特别慢的原因是什么?
我测试了下 Python 几大 MySQL 驱动的查询速度。
http://ww1.sinaimg.cn/large/6909e98fgy1fw6hf5vx7fj20sl0833zo.jpg
和预料的一样,pymysql 是最慢的,mysqlclient 很快,但是 mysql-connector-python 更快,但是只是在 Python 3.6 下最快,一旦到了 Python 3.7,反而比 pymysql 还慢,这是怎么回事?
Python中mysql-connector在Python 3.7下运行特别慢的原因是什么?
图片怎么不显示?
我遇到过类似问题,mysql-connector在Python 3.7下慢通常是因为默认使用了纯Python实现。试试换成mysql-connector-python的C扩展版本:
# 安装时指定带C扩展的版本
# pip install mysql-connector-python==8.0.33
import mysql.connector
import time
# 创建连接时启用C扩展
config = {
'user': 'your_username',
'password': 'your_password',
'host': 'localhost',
'database': 'your_database',
'use_pure': False # 关键参数:启用C扩展加速
}
start = time.time()
conn = mysql.connector.connect(**config)
cursor = conn.cursor()
# 执行查询
cursor.execute("SELECT * FROM your_table LIMIT 1000")
results = cursor.fetchall()
print(f"查询耗时: {time.time() - start:.2f}秒")
cursor.close()
conn.close()
如果还慢,检查下是不是网络延迟或者查询本身的问题。用use_pure=False强制启用C扩展能显著提升性能。
换用PyMySQL或aiomysql可能更快。
查询数据量 30w
求 benchmark 代码
就是最简单 select * from table 的查询啊
mysql-connector-python 带个加速扩展, 没有的话 fallback 到纯 python 就慢出翔了
pypi 上 3.7 以上版本的 whl 自带,3.7 没有, 你从源码安装吧
5 楼正解,3.6 的 mysql_connector_python-8.0.12-cp36-cp36m-win_amd64.whl 包带了编译好的 dll,而 3.7 用的通用包 mysql_connector_python-8.0.12-py2.py3-none-any.whl 没有预编译好的扩展
学习了,刚刚试了下从源码编译安装,速度又回来了。
[pymysql]
用时:11.067870310999979
[mysqlclient]
用时:2.3283727630000612
[mysql.connector]
用时:1.1639837800000805
安装代码
sudo /home/qzier/.pyenv/versions/3.7.0/bin/python setup.py install --with-mysql-capi=/usr/bin/mysql_config
benchmark 代码得提供吧。另外,Python 有类似于 Java 的 Flight Recorder 那种东西么。
可以弄一个火焰图,看一下到底性能瓶颈在什么地方
类似于 JMH 这样的,python 也应该有的吧
原来 pymysql 性能差距这么大 感谢楼主提供


