curl分析请求的各个部分耗时情况

curl 命令提供了 -w 参数,解释如下

-w, --write-out  
Make curl display information on stdout after a completed transfer. The format is a string that may contain plain text mixed with any number of variables. The format 
can be specified as a literal "string", or you can have curl read the format from a file with "@filename" and to tell curl to read the format from stdin you write 
"@-". 
The variables present in the output format will be substituted by the value or text that curl thinks fit, as described below. All variables are specified as %{vari‐ 
able_name} and to output a normal % you just write them as %%. You can output a newline by using 
, a carriage return with 
 and a tab space with 	. 

它能够按照指定的格式打印某些信息,里面可以使用某些特定的变量,而且支持 、 和 转义字符。提供的变量很多,比如 status_code 、 local_port 、 size_download 等等,这篇文章我们只关注和请求时间有关的变量(以 time_ 开头的变量)

文本文件 curl-format.txt 写入下面的内容:

[root@node ~]# cat curl-format.txt 
time_namelookup: %{time_namelookup}
 
time_connect: %{time_connect}
  
time_appconnect: %{time_appconnect}
  
time_redirect: %{time_redirect}
  
time_pretransfer: %{time_pretransfer}
  
time_starttransfer: %{time_starttransfer}
  
----------
 
time_total: %{time_total}


#变量解释如下
time_namelookup :DNS 域名解析的时候,就是把 https://zhihu.com 转换成 ip 地址的过程
time_connect :TCP 连接建立的时间,就是三次握手的时间
time_appconnect :SSL/SSH 等上层协议建立连接的时间,比如 connect/handshake 的时间
time_redirect :从开始到最后一个请求事务的时间
time_pretransfer :从请求开始到响应开始传输的时间
time_starttransfer :从请求开始到第一个字节将要传输的时间
time_total :这次请求花费的全部时间

看一下命令的输出

[root@node ~]# curl -w "@curl-format.txt" -o /dev/null -s -L "http://www.52py.com.cn"                                                                                                                              
time_namelookup: 0.124
 time_connect: 0.132
  time_appconnect: 0.257
  time_redirect: 0.282
  time_pretransfer: 0.257
  time_starttransfer: 15.315
  ----------
 time_total: 15.605

可以看到这次请求各个步骤的时间都打印出来了,每个数字的单位都是秒(seconds),这样可以分析哪一步比较耗时,方便定位问题。这个命令各个参数的意义:
  • -w :从文件中读取要打印信息的格式
  • -o /dev/null :把响应的内容丢弃,不关心,只关心请求的耗时情况
  • -s :不要打印进度条
从上面的输出,我们可以算出各个步骤的时间
  • DNS 查询:124ms
  • TCP 连接时间:pretransfter(257) - namelookup(124) = 133ms
  • SSL 协议处理时间: appconnect(257) - connect(132) = 125ms
  • 服务器处理时间:starttransfter(15.315) - pretransfer(257) = 15.058s
  • 内容传输时间:total(15.605) - starttransfer(15.315) = 290ms
原文地址:https://www.cnblogs.com/52py/p/11732006.html