Python 提高“的速度”;“发送100000个请求”;通过使用多进程和多线程的异步IO
首先,我希望尽可能快地使用一个连接发送多个请求。下面的代码运行良好且快速,但我希望它超越异步。回到我的问题上来,是否可以使用多线程或多处理并行运行此程序。我听说您可以使用ThreadPoolExecutor或ProcessPoolExecutorPython 提高“的速度”;“发送100000个请求”;通过使用多进程和多线程的异步IO,python,multithreading,python-asyncio,aiohttp,Python,Multithreading,Python Asyncio,Aiohttp,首先,我希望尽可能快地使用一个连接发送多个请求。下面的代码运行良好且快速,但我希望它超越异步。回到我的问题上来,是否可以使用多线程或多处理并行运行此程序。我听说您可以使用ThreadPoolExecutor或ProcessPoolExecutor import random import asyncio from aiohttp import ClientSession import time from concurrent.futures import ProcessPoolExecutor
import random
import asyncio
from aiohttp import ClientSession
import time
from concurrent.futures import ProcessPoolExecutor
async def fetch(sem,url, session):
async with sem:
async with session.get(url) as response:
return await response.read()
async def run(r):
url = "http://www.example.com/"
tasks = []
sem = asyncio.Semaphore(1000)
async with ClientSession() as session:
for i in range(r):
task = asyncio.ensure_future(fetch(sem, url.format(i), session)) #return a task
tasks.append(task)
responses = asyncio.gather(*tasks)
await responses
if __name__ == "__main__":
number = 10000
loop = asyncio.get_event_loop()
start = time.time()
loop.run_until_complete(run(number))
end = time.time() - start
print (end)
通过测试,它成功地在49秒内发送了大约10k的请求。
我需要快点,有什么建议吗?(线程,进程)ProcessPoolExecutor是执行真正的多重处理的一种方法。 对于您的用例,基本上就像您同时启动程序的多个副本一样。如果您的计算机上有所需的带宽和CPU,那么您应该能够通过使用ProcessPoolExecutor(max_workers=4)将性能提高4 但是,在每个子流程中都需要一个asyncio事件循环,因此可以执行以下操作:
def main(n):
loop = asyncio.get_event_loop()
loop.run_until_complete(run(n))
with concurrent.futures.ProcessPoolExecutor(max_workers=4) as exc:
exc.submit(main, 2500)
exc.submit(main, 2500)
exc.submit(main, 2500)
exc.submit(main, 2500)
作为运行
函数的旁注:您也不需要使用确保未来的
或任务,异步定义
函数的结果是一个协程,您可以直接等待或传递给asyncio.gather
async def run(r):
url = "http://www.example.com/"
sem = asyncio.Semaphore(1000)
async with ClientSession() as session:
coros = [fetch(sem, url.format(i), session) for i in range(r)]
await asyncio.gather(*coros)
你试过分析它吗?查看运行时的CPU使用情况?你有没有阅读过多线程的文档,并自己尝试过一些东西?因此,这不是一个“为我做事”的网站。顺便说一句,一个由互斥锁保护的单一连接一次只能有一个线程使用它将成为瓶颈。它处理数据的速度如此之快,许多线程都会坐在互斥锁上等待轮到它们。所以从技术上讲,在这个方向上,它不能再快了吗?先生,有其他方法的建议吗?