#3215·httpx

提高异步性能。

作者: MarkusSintonen创建于 2024年6月4日更新于 2026年2月25日
标签perf

" httpx " (0.27.0)中似乎有一些业绩问题,因为其业绩比 " aiohttp " (3.9.4)和同时运行的请求(Python 3.12)要差得多。 以下基准显示,与aiohttp'相比,同时运行20项请求的速度慢于httpx'的10x以上。 该基准具有非常基本的 " httpx " 用途,可用于使用有限的货币进行多次获取请求。 脚本会输出一个图表,显示每个GET请求的持续时间与“httpx”之间的巨大持续时间差异。

图1.

2zz
# 要求.txt:
# httpx == 0: 2:
{\fn黑体\fs22\bord1\shad0\3aHBE\4aH00\fscx67\fscy66\2cHFFFFFF\3cH808080}你觉得呢?
{\fn方正黑体简体\fs18\b1\bord1\shad1\3cH2F2F2F}美国著名女演员
{\fn方正粗倩简体\fs12\an8\1cHFFFF00\b0}
# 1. 启动服务器: Python长凳.py服务器
# 2. 运行客户端测试: Python 长凳.py客户端

导入 Ayncio
导入 sys
从打入中导入 Any, Coroutine, 指示器
导入 aiohttp
导入时间
导入 httpx
从 aiohttp 导入网页
将 matplotlib.pyplot 导入为 plt


港号=1234
URL=f"http://localhost:{port}/req" (中文(简体) ).
* 2000年。
请求=100
结 论=20


def run web 服务器 ():
async def handle(   request) : (中文(简体) ).
返回网络。 答复(文本=RESP)

app=网络. 应用程序( )
app.add routes ([web.get ('/req', handle])) (中文(简体) ).
网络.run app(应用程序,主机="localhost",端口=port)


def 持续时间( 启动: 浮点) - > 英寸 :
返回 int ((time.monotonic () - start) * 1000) 中


async def run  requests(轴:plt.Axes) :
async def 集合  有限  货币( coros: 惯性 [Coroutine [Any, Any, Any]]) :
sem = asyncio. (英语). 司马磷(CONCURRENCY)
async def coro  with sem(coro) :
与 sem 同步:
返回等待 Coro 时
返回等待 ayncio.gather(*(coro  with sem(c) for c in coros)) 。

aync def httpx get(会话:httpx.AsyncClient,时间:list[int]):
开始=时间.monotonic ()
res = 等待会话. request ("GET", URL)
== (RESP)
声明 Res.status code === 200, f"status code =res.status code}" 维基语录链接:名人名言 - 文学作品 - 谚语 - 谚语
时间。附录(期限(开始))

aync def aiohttp get(会话:aiohttp. Client Session,时间:列表[int]):
开始=时间.monotonic ()
与会话同步。 request("GET"), URL 为 res:
profile (await res.read ()) == (RESP)
声明第200,f"status *=res.status}"
时间。附录(期限(开始))

以 httpx.AsyncClient () 作为会话 :
热身
等待 ayncio.gather( *( httpx  get( session, [] for   in range(REQULES)))) 。

时间 = []
开始=时间.monotonic ()
正在等待 collect  有限  货币 (( httpx  get (会话, 时间)) for   in range(REQULES)))
轴.plot ([*range(REQULES)], 时间, 标签=f"httpx (tot- duration( start)}ms)")

以 aiohttp. Client Session () 作为会话 :
热身
等待 ayncio.gather (*(aiohttp get (session, [] for   in range(REQULES))) ) (中文(简体) ).

时间 = []
开始=时间.monotonic ()
等待时
. . . . . . .