Python - 测量 DNS 和往返时间

Python - Measuring DNS and roundtrip time

我正在编写 python 脚本来测量对 DNS 服务器的响应时间和从 Web 服务器获取数据的响应时间。

我采取的做法如下

  1. 首先使用套接字 module.Let 调用此函数 A
  2. 测量 DNS 查找时间
  3. 在 subprocess 模块中使用 ping 命令测量 Web 服务器的响应。我们称这个函数为 B

我在代码中先调用函数 A,然后调用函数 B。

该解决方案工作正常,但我怀疑这是否是正确的方法。

原因是,DNS 查找被调用了两次(一次在函数 A 中,然后在函数 B 中)。所以函数 B 中的 DNS 查找时间总是远小于函数 A 中计算的时间。

函数A代码

                startTime = datetime.datetime.now()
                ip = socket.gethostbyname(host)
                endTime = datetime.datetime.now()
                diff = (endTime - startTime).total_seconds() * 1000 

函数B代码

    resp = subprocess.popen(['ping','-c 3','host.com'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    out,err = resp.communicate()

谢谢

DNS lookup is being called twice (once in function A & then in function B).

您可以通过将 gethostbyname() 返回的 IP 地址用于后续 HTTP 请求来消除此问题。

如果愿意,您还可以将 HTTP 请求的时间拆分为协议握手所花费的时间,以及传输返回数据所花费的时间。对于以下代码...

import socket
import time
import urllib2

hostname = 'whosebug.com'

dns_start = time.time()
ip_address = socket.gethostbyname(hostname)
dns_end = time.time()

url = 'https://%s/' % ip_address
req = urllib2.Request(url)
req.add_header('Host', hostname)

handshake_start = time.time()
stream = urllib2.urlopen(req)
handshake_end = time.time()

data_start = time.time()
data_length = len(stream.read())
data_end = time.time()

print 'DNS time            = %.2f ms' % ((dns_end - dns_start) * 1000)
print 'HTTP handshake time = %.2f ms' % ((handshake_end - handshake_start) * 1000)
print 'HTTP data time      = %.2f ms' % ((data_end - data_start) * 1000)
print 'Data received       = %d bytes' % data_length

...我明白...

DNS time            = 1.77 ms
HTTP handshake time = 170.66 ms
HTTP data time      = 315.76 ms
Data received       = 242817 bytes

请注意,握手时间包括 TCP 握手、SSL 握手(如果适用)、HTTP 请求和 HTTP 响应所需的时间 headers,但通常还包括远程服务器生成 HTTP 响应 body.