requests 为什么慢 urllib3 如此之多?

164 天前
 annoygaga

目前使用 requests 库去进行一些 api 的访问,惊讶的发现 requests 库速度相较于 urllib3 慢非常多

$ url = "https://httpbin.org"

$ %timeit r = requests.get(url)

119 ms ± 42.5 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

$ %timeit r = httpx.get(url)

%117 ms ± 17.6 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

$ http = urllib3.PoolManager()
$ %timeit response = http.request("GET", url)
The slowest run took 6.87 times longer than the fastest. This could mean that an intermediate result is being cached.
10.6 ms ± 6.91 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)

其中还尝试了 session 等方法,貌似也没有变快,上面的是多次的测试,我还做了一次请求的测试,看上去也是很慢

看了看源码和原理,想象不出来这个速度差来自哪里?

需求就是请求网址需要快,但不一定需要多次请求

2611 次点击
所在节点    Python
24 条回复
annoygaga
164 天前
这里也试了带 json 数据的 post 方法,结果也是一样的
WildCat
164 天前
感觉 urllib3.PoolManager() 是一个 connection pool ?
有 re-use 现成的 TCP 链接
ysc3839
164 天前
控制变量都没做好,requests 是直接 get 的,utllib3 怎么就用了 PoolManager ?
annoygaga
164 天前
@WildCat 我试过 session ,也是一样的结果
annoygaga
164 天前
@ysc3839 我试过 session 和 httpx 的 withclient ,也是一样的结果
annoygaga
164 天前
而且单次请求的速度,试了几次,也是 urllib3 快一些
annoygaga
164 天前
```
%timeit r = sess.get(url)
The slowest run took 16.83 times longer than the fastest. This could mean that an intermediate result is being cached.
20.8 ms ± 21.9 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
```

补一下 session 的结果,会快一些

但是我的需求其实是单次请求快(不求复用链接。。。
009694
164 天前
requests 是 urllib3 的封装。 你怎么可能期望更高层的封装比底层调用快?
annoygaga
164 天前
@009694 我看了源码,我也不解呀
justFxxk2060
164 天前
import requests
session = requests.Session()
url = "https://httpbin.org"
%timeit session.get(url)

这样试试

@ysc3839 是对的
justFxxk2060
164 天前
Session 单次虽然没有意义,但是也能复用底层 TCP 连接

比如你先运行
http = urllib3.PoolManager()
然后运行
session.get(url)

指不定也会更快一些
zeusho871
164 天前
119 117 10.6ms?相差 10 倍 这么离谱的吗
liprais
164 天前
"The slowest run took 6.87 times longer than the fastest. This could mean that an intermediate result is being cached."
这几行字是看不见么?
annoygaga
164 天前
@zeusho871 你可以试试
annoygaga
164 天前
@liprais 我已经在上面回复关于链接池的测试了,而且我的需求是一次请求,非多次,一次请求下也是类似的效果
u823tg
164 天前
不都用 httpx 了吗还是我好久没写 python 了,又转回到 requests 风向了
annoygaga
164 天前
@u823tg httpx 也测了,参考上面,with client 下和 requests 的 session 差不多
mengzhuo
164 天前
大概率是 cache ,每次请求带个随机数参数试试?
linhua
164 天前
单次时间,那就不要用 timeit 测量,timeit 是 多次请求 平均的时间。
Alias4ck
164 天前

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/995381

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX