接口测试中可以可以使用httpx进行异步调用,下面对比一下异步调用和同步调用的速度
异步调用的代码如下
async ==》发音athink、表示异步
await ==》饿威特
# 异步调用 import httpx import asyncio import time async def request(client): resp = await client.get('http://httpbin.org/get') result = resp.json() async def main(): async with httpx.AsyncClient() as client: # 100 次调用 task_list = [] for _ in range(100): req = request(client) task = asyncio.create_task(req) task_list.append(task) await asyncio.gather(*task_list) if __name__ == "__main__": #开始 start = time.time() asyncio.run(main()) # 结束 end = time.time() print(f'异步:发送100次请求,耗时:{end - start}')
结果:异步:发送100次请求,耗时:1.1421504020690918
# 同步调用 import time import httpx def make_request(client): resp = client.get('http://httpbin.org/get') result = resp.json() def main(): session = httpx.Client() # 100 次调用 for _ in range(100): make_request(session) if __name__ == '__main__': # 开始 start = time.time() main() # 结束 end = time.time() print(f'同步:发送100次请求,耗时:{end - start}') 同步:发送100次请求,耗时:24.393028020858765