如何同时使用Python多处理和异步IO?
嗨, 我有2000个api地址。 我需要在一个虚拟机中同时调用2000。 因此,我使用asyncio库修改了上述代码。 但是,这种解决办法并不令人满意。 如何提高并行处理的效果?如何同时使用Python多处理和异步IO?,python,python-asyncio,python-3.7,python-multiprocessing,Python,Python Asyncio,Python 3.7,Python Multiprocessing,嗨, 我有2000个api地址。 我需要在一个虚拟机中同时调用2000。 因此,我使用asyncio库修改了上述代码。 但是,这种解决办法并不令人满意。 如何提高并行处理的效果? 我想我必须同时使用多处理和异步IO。您没有具体说明“解决方案不令人满意”的含义。你有例外吗?是不是太慢了?在切换到多处理之前,您可以尝试一些事情——例如,不要为每个请求创建新的会话(客户端)。在main()中只创建一次会话,并将其传递给每个request\u test()。是的,它太慢了……而且我不明白“在main()
我想我必须同时使用多处理和异步IO。您没有具体说明“解决方案不令人满意”的含义。你有例外吗?是不是太慢了?在切换到多处理之前,您可以尝试一些事情——例如,不要为每个请求创建新的会话(客户端)。在
main()
中只创建一次会话,并将其传递给每个request\u test()
。是的,它太慢了……而且我不明白“在main()和bla~中只创建一次会话”我能看到示例代码吗?将行async with httpx.AsyncClient()作为客户端
移动到main
函数中。将client
作为第二个参数传递给request\u test
,即将request\u test(url)
替换为request\u test(url,client)
。最后,修改request\u test
以接受client
作为参数。我还建议您阅读一篇关于asyncio的好的介绍,例如。这种方式需要更多的时间,可能您在服务器端受到限制,或者服务器根本无法提供您想要的吞吐量。您是否尝试过并行运行curl
或类似程序来测量这样得到的计时?
import asyncio
import httpx
from datetime import datetime
async def request_test(url):
async with httpx.AsyncClient() as client:
r = await client.get(url, timeout=None, headers=None)
return len(r.text)
async def main(rest_api_url_list ):
futures = [asyncio.ensure_future(request_test(url)) for url in rest_api_url_list ]
results = await asyncio.gather(*futures)
print(results)
print(len(results))
start = datetime.now()
rest_api_url_list = [~~~~~~~~~~~~~] # 2000EA
loop = asyncio.get_event_loop()
loop.run_until_complete(main(rest_api_url_list ))
loop.close()
end = datetime.now()