gpt4 book ai didi

python - 我不知道通常使用python aiomysql。运行时间(当 aiomysql 不使用时)与 aiomysql 使用时的运行时间相同

转载 作者:行者123 更新时间:2023-11-29 05:57:18 34 4
gpt4 key购买 nike

我使用 aiomysql。我异步访问mysql。所以我使用aiomysql。但是运行时间(不使用aiomysql时)与使用aimysql时的运行时间相同。

from sqlalchemy import create_engine
import pymysql
pymysql.install_as_MySQLdb()
import pandas as pd

engine = create_engine("mysql+mysqldb://root:"+"qhdks12#$"+"@localhost/stock", encoding='utf-8')
conn = pymysql.connect(host='localhost', user='root', password="qhdks12#$", db='stock', charset='utf8')
cursor = conn.cursor()
def test():
for i in range(10):
sql = "select * from test;"
data = pd.read_sql(sql, conn, index_col=None)
%timeit test()

以上代码,aiomysql没有使用。在 Jupyter Notebook 中,test() 函数运行时间为“3.1 s ± 39.3 ms”

import asyncio
import aiomysql as aiomysql
import pandas as pd

async def main(loop):

pool = await aiomysql.create_pool(host='127.0.0.1', port=3306, user='root', password='qhdks12#$', db='stock', loop=loop)
for i in range(2):
await test(pool, loop)

async def test(pool, loop):
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute("select * from test;")
rows = ()
rows = await cur.fetchall()
result = pd.DataFrame.from_records(list(rows))

loop = asyncio.get_event_loop()
%timeit loop.run_until_complete(main(loop))

以上代码,aiomysql使用。在 Jupyter Notebook 中,主(循环)函数运行时间为“3.05 s ± 107 ms per loop”

运行时间相同。我认为上面的代码没有将数据库与异步连接。

所以,平时对aiomysql不是很了解。如何将数据库与异步连接???

最佳答案

以下代码是同步的。如果您大声朗读它,您将循环并等待每个测试完成后再继续。

for i in range(2):
await test(pool, loop)

要异步发送您的请求,您可以使用 wait 或 gather 来等待所有请求。

futures = []
for i in range(10):
futures.append( test(pool) )

done, pending = await asyncio.wait( futures, timeout=2 )

关于python - 我不知道通常使用python aiomysql。运行时间(当 aiomysql 不使用时)与 aiomysql 使用时的运行时间相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48247648/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com