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

2024-03-29 14:35:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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)

它给了我一个结果

^{pr2}$

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


Tags: httpsimportgettimewww时间requestsstart
1条回答
网友
1楼 · 发布于 2024-03-29 14:35:49

我用一个人工延迟的Web服务器做了一些测试:

nc -l 8080

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

^{pr2}$

将此粘贴在服务器终端上发出此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个字节(hello\n),所以这是未完成的。我又等了五秒钟,然后粘贴了这段文字:

world

这就用剩下的6个字节(world\n)完成了回复。在客户端,我看到了结果:

0:00:05.185509 10.8904578686

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

相关问题 更多 >