前言
当我们访问一个网站或者网站接口服务,想知道"时间都去哪里了",这时候我们借助工具来分析。
可以将时间大致分为两部分:一部分是从我们请求到网站服务端所经历的耗时,另一部分是服务端自身处理该服务完毕后响应回来的时间,这些都是可以作为后面结果分析的判断依据。
下面将介绍两个方案,仅供参考。
第一种方案:
使用系统curl命令模拟网站服务请求,得到各个时间段的时间。
需要注意的是:请确保curl 是最新版本,否则一些参数选项无法使用。
例子:
$ curl -w "Result: dnslookup: %{time_namelookup} connect: %{time_connect} appconnect: %{time_appconnect} pretransfer: %{time_pretransfer} starttransfer: %{time_starttransfer} total: %{time_total} ---- time_redirect: %{time_redirect} ---- size: %{size_download}" "https://www.baidu.com" 百度一下,你就知道
新闻 hao123 地图 视频 贴吧 登录 更多产品
关于百度 About Baidu
©2017 Baidu 使用百度前必读 意见反馈 京ICP证030173号
Result: dnslookup: 0.005 connect: 0.009 appconnect: 0.128 pretransfer: 0.128 starttransfer: 0.134 total: 0.134 ---- time_redirect: 0.000 ---- size: 2443
参数:
- time_namelookup:DNS解析时间,从请求开始到DNS解析完毕所用时间
- time_connect:建立到服务器的 TCP 连接所用的时间
- time_appconnect:从起始到应用侧(SSL)连接/握手完成的耗时。(在7.19.0 版加入)
- time_pretransfer:从开始至准备开始传输数据的时间
- time_starttransfer:在发出请求之后,Web 服务器返回数据的第一个字节所用的时间
- time_total:全部操作耗费的时间,单位为秒。精确到毫秒。
- size_download:下载的总字节数。
- speed_download:下载速度,单位-字节每秒。
从上面的例子可以看到
- DNS解析耗时:0.005秒
- TCP建立连接的耗时:(0.009-0.005)= 0.004秒
- SSL握手完成耗时:(0.128-0.009)= 0.119秒
- server处理数据的时间:(0.134-0.128)= 0.006秒
- 总体的耗时:0.134秒
- 整个过程没有redirect,所以redirect的耗时为0
上面还有个小技巧:
$ cat ~/.curlrc -w "Result: dnslookup: %{time_namelookup} connect: %{time_connect} appconnect: %{time_appconnect} pretransfer: %{time_pretransfer} starttransfer: %{time_starttransfer} total: %{time_total} ---- time_redirect: %{time_redirect} ---- size: %{size_download}"$ curl "https://www.baidu.com"
我们把-w参数的值写到curl配置文件~/.curlrc,这样我们按照之前的curl命令访问具体网址就可以得到各个时间。
第二种方案:
当你拥有Python的环境时,可以借助一个库,可以方便清晰的了解耗时,这个库就是httpstat。
注意:该工具还是依赖底层curl命令,所以确保curl是最新版本。
这里我以Python3环境为例,介绍下如何使用。
- 安装库
$ pip3 install httpstat
- 检查httpstat命令是否存在
$ which httpstat~/3rd/Python-3.7.4/bin/httpstat
- 访问网站
$ httpstat "https://www.baidu.com"Connected to 163.177.151.110:443 from 10.10.10.10:41350HTTP/1.1 200 OKAccept-Ranges: bytesCache-Control: private, no-cache, no-store, proxy-revalidate, no-transformConnection: keep-aliveContent-Length: 2443Content-Type: text/htmlDate: Mon, 25 May 2020 03:14:53 GMTEtag: "58860402-98b"Last-Modified: Mon, 23 Jan 2017 13:24:18 GMTPragma: no-cacheServer: bfe/1.0.8.18Set-Cookie: BDORZ=27315; max-age=86400; domain=.baidu.com; path=/Body stored in: /tmp/tmp35tdqpkp DNS Lookup TCP Connection TLS Handshake Server Processing Content Transfer[ 41ms | 5ms | 45ms | 6ms | 1ms ] | | | | | namelookup:41ms | | | | connect:46ms | | | pretransfer:91ms | | starttransfer:97ms | total:98ms
是不是很直观? so easy。
总结:
- 如果你不想用python,那么第一种方案最直接高效。
- 如果你想用python,那么第二种方案显示效果最佳。
今天你get 到了吗?喜欢的话,关注收藏下。