为什么 Python 3 http.client 比 python-requests 快这么多?

2024-04-24

我今天测试了不同的 Python HTTP 库,我意识到http.client https://docs.python.org/3/library/http.client.html库的执行速度似乎比requests http://docs.python-requests.org/en/master/.

要测试它,您可以运行以下两个代码示例。

import http.client

conn = http.client.HTTPConnection("localhost", port=8000)
for i in range(1000):
    conn.request("GET", "/")
    r1 = conn.getresponse()
    body = r1.read()
    print(r1.status)

conn.close()

这是使用 python-requests 执行相同操作的代码:

import requests

with requests.Session() as session:
    for i in range(1000):
        r = session.get("http://localhost:8000")
        print(r.status_code)

如果我启动 SimpleHTTPServer:

> python -m http.server

并运行上面的代码示例(我使用的是Python 3.5.2)。我得到以下结果:

http.客户端:

0.35user 0.10system 0:00.71elapsed 64%CPU 

python 请求:

1.76user 0.10system 0:02.17elapsed 85%CPU 

我的测量和测试正确吗?你也能复制它们吗?如果是的话有谁知道里面发生了什么http.client这让它变得更快?为什么处理时间有如此大的差异?


根据对两者的分析,主要区别似乎是requests版本正在为每个请求进行 DNS 查找,而http.client版本就这样做了一次。

# http.client
ncalls  tottime  percall  cumtime  percall filename:lineno(function)
     1974    0.541    0.000    0.541    0.000 {method 'recv_into' of '_socket.socket' objects}
     1000    0.020    0.000    0.045    0.000 feedparser.py:470(_parse_headers)
    13000    0.015    0.000    0.563    0.000 {method 'readline' of '_io.BufferedReader' objects}
...

# requests
ncalls  tottime  percall  cumtime  percall filename:lineno(function)
     1481    0.827    0.001    0.827    0.001 {method 'recv_into' of '_socket.socket' objects}
     1000    0.377    0.000    0.382    0.000 {built-in method _socket.gethostbyname}
     1000    0.123    0.000    0.123    0.000 {built-in method _scproxy._get_proxy_settings}
     1000    0.111    0.000    0.111    0.000 {built-in method _scproxy._get_proxies}
    92000    0.068    0.000    0.284    0.000 _collections_abc.py:675(__iter__)
...

您将主机名提供给http.client.HTTPConnection()一次,所以它会调用是有道理的gethostbyname once. requests.Session可能可以缓存主机名查找,但显然不能。

编辑:经过一些进一步的研究,这不仅仅是一个简单的缓存问题。有一个函数用于确定是否绕过最终调用的代理gethostbyname无论实际请求本身如何。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 Python 3 http.client 比 python-requests 快这么多? 的相关文章

随机推荐