通过python-requests测量请求时间的两种方法之间存在巨大差距



我正在尝试使用python请求来测量某个请求的响应时间。

import requests
import time
start = time.time()
r = requests.get("https://www.dl.soc.i.kyoto-u.ac.jp/index.php/members/")
end = time.time()
print(end - start)
print(r.elapsed.seconds)

它给了我一个结果

64.67747116088867
0.631163

谁能解释一下这种巨大差距的原因?谢谢。顺便说一句,当我在Google-Chrome上尝试相同的请求时,实际上第一个结果就是我想要的。

我用人为延迟的网络服务器做了一些测试:

nc -l 8080

然后在 Python 会话的另一个终端中:

import time, requests
a=time.time()
r = requests.get("http://localhost:8080/")
b=time.time()
print r.elapsed, b-a

将此发出的 HTTP 请求粘贴到服务器终端上:

GET / HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Accept-Encoding: gzip, deflate
Accept: */*
User-Agent: python-requests/2.9.1

我等了5秒钟,然后将这个回复粘贴到服务器中:

HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 12
Connection: keep-alive
Keep-Alive: timeout=15
Date: Thu, 04 Jan 2018 10:12:09 GMT
Server: Apache
Last-Modified: Wed, 09 Dec 2015 13:57:24 GMT
ETag: "28bd-52677784b6090"
Accept-Ranges: bytes
hello

我说了 12 个字节,但只发送了 6 个 (hellon(,所以这还没有完成。 我又等了五秒钟,然后粘贴了这条文字:

world

这完成了剩余六个字节(worldn(的回复。 在客户端中,我看到结果出现:

0:00:05.185509 10.8904578686

因此,显然r.elapsed是到第一个字节的时间(TTFB(,而对requests.get()的调用仅在收到整个消息后终止(到最后一个字节的时间,TTLB(。

相关内容

最新更新