下面是aiohttp异步请求,与常用的requests请求比较,差距还是蛮大的,其中ensure_future
这种方式与for循环调用也存在一些差距
import asyncio
import aiohttp
import time
async def task_req():
# 耗时0.1483309268951416s
async with aiohttp.ClientSession() as session:
async with session.get('http://baidu.com') as resp:
print(resp.status)
async def for_req():
# 耗时2.0457730293273926
async with aiohttp.ClientSession() as session:
for i in range(100):
async with session.get('https://baidu.com') as resp:
print(resp.status)
def sync_req():
# 耗时 11.768546104431152
for i in range(100):
requests.get('https://baidu.com')
if __name__ == '__main__':
s = time.time()
# 第一组
# sync_req()
# 第二组
loop = asyncio.get_event_loop()
# tasks = [asyncio.ensure_future(task_req()) for i in range(100)]
# loop.run_until_complete(asyncio.wait(tasks))
# 第三组
loop.run_until_complete(for_req())
print(time.time() - s)