requests 为什么慢 urllib3 如此之多?

查看 294|回复 11
作者: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 等方法,貌似也没有变快,上面的是多次的测试,我还做了一次请求的测试,看上去也是很慢
看了看源码和原理,想象不出来这个速度差来自哪里?
需求就是请求网址需要快,但不一定需要多次请求

mean, url, runs, Loops

annoygaga
OP
  
这里也试了带 json 数据的 post 方法,结果也是一样的
WildCat   
感觉 urllib3.PoolManager() 是一个 connection pool ?
有 re-use 现成的 TCP 链接
ysc3839   
控制变量都没做好,requests 是直接 get 的,utllib3 怎么就用了 PoolManager ?
annoygaga
OP
  
@WildCat 我试过 session ,也是一样的结果
annoygaga
OP
  
@ysc3839 我试过 session 和 httpx 的 withclient ,也是一样的结果
annoygaga
OP
  
而且单次请求的速度,试了几次,也是 urllib3 快一些
annoygaga
OP
  
```
%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   
requests 是 urllib3 的封装。 你怎么可能期望更高层的封装比底层调用快?
annoygaga
OP
  
@009694 我看了源码,我也不解呀
您需要登录后才可以回帖 登录 | 立即注册

返回顶部