如何使用cURL获得请求/响应具体耗时?

hello,老伙计们,又有半个多月没见了,今天给大家分享一个干货编程小技巧,上至架构师、下至开发者、运维男、QA, 得此利器,事半功倍。

cURL支持格式化输出请求的详细信息(请参阅cURL手册页的-w、–write out<format>获取更多信息)。

如题,我们将只关注如何知晓cURL请求的时间细节, 下面时间以s为单位。

1. 创建一个文本文件curl-format.txt, 粘贴下面内容

   time_namelookup:  %{time_namelookup}s\n
        time_connect:  %{time_connect}s\n
     time_appconnect:  %{time_appconnect}s\n
    time_pretransfer:  %{time_pretransfer}s\n
       time_redirect:  %{time_redirect}s\n
  time_starttransfer:  %{time_starttransfer}s\n
                     ----------\n
          time_total:  %{time_total}s\n
复制代码

2.发起请求

url -w "@curl-format.txt" -o /dev/null -s "http://wordpress.com/"

在windows机器上是curl -w "@curl-format.txt" -o NUL -s "http://wordpress.com/"

旁白解释

-w "@curl-format.txt" 通知cURL使用格式化的输出文件
-o /dev/null 将请求的输出重定向到/dev/null
-s 通知cURL不显示进度条
"http://wordpress.com/" 是我们请求的URL,请使用引号包围(尤其当你的URL包含&查询字符串)

文本输出

 time_namelookup:  0.001s
      time_connect:  0.037s
   time_appconnect:  0.000s
  time_pretransfer:  0.037s
     time_redirect:  0.000s
time_starttransfer:  0.092s
                   ----------
        time_total:  0.164s
复制代码

输出的啥意思呢? 我解释一下:

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

制作成Linux/Mac快捷命令(alise 别名)

alias curltime="curl -w \"@$HOME/.curl-format.txt\" -o /dev/null -s "

制作成Linux/Mac 独立脚本

脚本不需要单独的包含格式化的文本。

在可执行路径中,创建名为curltime的文件,粘贴下面内容:

#!/bin/bash

curl -w @- -o /dev/null -s "$@" <<'EOF'
    time_namelookup:  %{time_namelookup}\n
       time_connect:  %{time_connect}\n
    time_appconnect:  %{time_appconnect}\n
   time_pretransfer:  %{time_pretransfer}\n
      time_redirect:  %{time_redirect}\n
 time_starttransfer:  %{time_starttransfer}\n
                    ----------\n
         time_total:  %{time_total}\n
EOF
复制代码

制作成windows快捷方式(bat批处理)

把下面的命令写入curltime.bat:
curl -w "@%~dp0curl-format.txt" -o NUL -s %*

以上手段后,curltime wordpress.org就可以拿到cURL的请求耗时。


cURL还有一个小技巧,模拟连接/传输超时。

连接超时时间用--connect-timeout参数来指定,数据传输的最大允许时间用-m参数来指定。

连接超时的话,出错提示形如:
curl: (28) connect() timed out!

数据传输的最大允许时间超时的话,出错提示形如:
curl: (28) Operation timed out after 2000 milliseconds with 0 bytes received