我有一个API" localhost / service"当串行请求时,平均需要2秒返回,当我设置10个线程并行请求时,大约需要8秒。我想使用asyncio复制这些数字,没有线程。我决定这样做的方法是遵循这个article's代码并将信号量设置为10.对于前20个左右的请求,我得到的响应时间为8秒,但之后响应时间开始急剧增加。我一直在使用邮递员请求服务器,并且它始终返回8秒的响应时间,而使用asyncio的此脚本报告每个请求超过一分钟的时间。我在这里做错了什么?
import time
import asyncio
from aiohttp import ClientSession
async def fetch(url, session):
start = time.monotonic()
async with session.get(url) as response:
end = round(time.monotonic() - start, 4)
print("response time: {}".format(end))
return await response.read()
async def bound_fetch(sem, url, session):
# Getter function with semaphore.
async with sem:
await fetch(url, session)
async def run(r):
url = 'http://localhost:8080/service'
tasks = []
# create instance of Semaphore
sem = asyncio.Semaphore(10)
# Create client session that will ensure we dont open new connection
# per each request.
async with ClientSession() as session:
for i in range(r):
# pass Semaphore and session to every GET request
task = asyncio.ensure_future(bound_fetch(sem, url.format(i), session))
tasks.append(task)
responses = asyncio.gather(*tasks)
await responses
number = 10000
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(run(number))
loop.run_until_complete(future)
答案 0 :(得分:0)