最近工作中遇到一个问题,某个请求的响应特别慢,因此我就希望有一种方法能够分析到底请求的哪一步耗时比较长,好进一步找到问题的原因。
curl 命令提供了 -w 参数,这个参数在 manpage 是这样解释的:

  1. -w, --write-out
  2. 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
  3. 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
  4. "@-".
  5. 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
  6. able_name} and to output a normal % you just write them as %%. You can output a newline by using \n, a carriage return with \r and a tab space with \t.

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

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

  1. time_namelookup: %{time_namelookup}\n
  2. time_connect: %{time_connect}\n
  3. time_appconnect: %{time_appconnect}\n
  4. time_redirect: %{time_redirect}\n
  5. time_pretransfer: %{time_pretransfer}\n
  6. time_starttransfer: %{time_starttransfer}\n
  7. ----------\n
  8. time_total: %{time_total}\n

调用一个网站

  1. curl -w "@curl-format.txt" -o /dev/null -s -L "http://cizixs.com"

curl 参数

  1. -w :从文件中读取要打印信息的格式
  2. -o /dev/null :把响应的内容丢弃,因为我们这里并不关心它,只关心请求的耗时情况
  3. -s :不要打印进度条

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

文档更新时间: 2022-06-10 10:57   作者:张尚