python - python 中的 MySQL 查询需要很多时间,postgres 查询工作正常

标签 python mysql performance

我正在使用时间分析器来优化我的 python 脚本。事实证明,mysql 查询在我的 python 脚本中花费了大量时间。总共只有 19 个查询。根据 cProfile 的报告,这 19 个 mysql 查询占用了 7.44 秒。

以下是完整的脚本足迹,包含 mysql 查询和以秒为单位的相应查询时间。

$ python -m cProfile -s time myscript.py 
MYSQL Queries
SELECT column FROM table WHERE foreign_key = 1 AND somecolumn='val1'
0.378623008728
SELECT column FROM table WHERE foreign_key = 1 AND somecolumn='val2'
0.379124879837
...
SELECT column FROM table WHERE foreign_key = 1 AND somecolumn='val19'
0.377450942993

   60122 function calls (59599 primitive calls) in 7.634 CPU seconds

   Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
       20    7.440    0.372    7.440    0.372 {method 'query' of '_mysql.connection' objects}
       22    0.025    0.001    0.025    0.001 {method 'execute' of 'psycopg2._psycopg.cursor' objects}
        2    0.008    0.004    0.008    0.004 {method 'commit' of 'psycopg2._psycopg.connection' objects}
     1299    0.007    0.000    0.011    0.000 posixpath.py:59(join)
      982    0.007    0.000    0.007    0.000 {posix.lstat}
      429    0.006    0.000    0.010    0.000 text_file.py:162(readline)
        1    0.006    0.006    0.006    0.006 {psycopg2._psycopg.connect}
        1    0.006    0.006    0.025    0.025 __init__.py:18(<module>)
        2    0.004    0.002    0.007    0.004 connections.py:62(__init__)
      110    0.004    0.000    0.027    0.000 posixpath.py:344(realpath)
       20    0.004    0.000    0.004    0.000 {method 'store_result' of '_mysql.connection' objects}

...

谁能帮我看看是什么原因?

谢谢

最佳答案

可能你忘了 create an index(foreign_key, somecolumn) 上导致 MySQL 需要执行全表扫描才能找到数据。您可以通过运行 EXPLAIN 来查看这一点:

EXPLAIN SELECT column FROM table WHERE foreign_key = 1 AND somecolumn='val1'

关于python - python 中的 MySQL 查询需要很多时间,postgres 查询工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7483261/

相关文章:

python - 拆分后与 Python 的缩进不一致

python - 有没有一种方法可以将带有条形图的 3 条线图绘制为具有不同 y 轴的一个图形?

python - 如何在 vs code 中缩进 jupyter 单元格/ block

mysql - 如何在 MySQL 中存储 Coldfusion #variable# 并从数据库输出变量值(而不是变量名称)?

MySQL & 嵌套集 : slow JOIN (not using index)

Python [<generator expression>] 至少比 list(<generator expression>) 快 3 倍?

python - 将字符串转换为 int python

Mysql gem 和 Rails3

php - 如何在 MySQL 数据库中存储版本号

performance - 如何减少第一字节时间或第一加载时间