DNS解析域名对aiohttp请求发送耗时的影响
最近学习python+aiohttp做压力测试,遇到问题就是请求的响应时间与真实响应时间不一致。最后分析是由于dns解析耗时导致。
1、不使用dns解析缓存(ipconfig/flushdns),平均每个请求时长在13s左右
2、使用本地hosts指定ip地址后进行请求,平均请求时间在0.74。
以下是简单测试代码
n = 300
url = "https://www.xxxx.com/zh-cn/"
async def task(session,url):
async with session.get(url) as res:
await res.text(encoding="utf8")
return 1
@api_response_time
async def test():
connector = aiohttp.TCPConnector(limit=20, force_close=True)
async with aiohttp.ClientSession(connector=connector) as session:
return await task(session,url)
async def create_task():
task_list = [asyncio.create_task(test()) for i in range(n)]
await asyncio.wait(task_list)
return task_list
loop = asyncio.get_event_loop()
task_res = loop.run_until_complete(create_task())
avg_time = round(sum([i.result()["run_time"] for i in task_res]) / n,2)
print(avg_time)