如何使用cURL获得请求和响应时间?

全栈码农画像

共 1584字,需浏览 4分钟

 · 2021-12-14

2f1fbe631c0bb72cad60dd59d63d8384.webp

✎ 码甲说  

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


cURL在我的眼里,就是一个httpClient手办,老伙计们知道怎么获得cURL请求的具体耗时吗?  🙃

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

如题,我们只关注如何知晓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 域名解析的时间,就是把http://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

  9b02350d1a5148dd2fca129648dd30c5.webp

有关[Http持久连接]的一切,卷给你看

HTTP1.1 Keep-Alive到底算不算长连接?

宝藏好物gRPCurl

SignalR 开发到生产部署闭坑指南

SignalR在React/Go技术栈的实践

我是状态机, 一颗永远骚动的机器引擎

你怕是对MD5算法有误解


0201b99d8385d19e4e5e30e47a08767e.webp

点个在看你最好看

f433795e85e618397c34633491be9580.webp

仅代表此刻认知,文章永久更新地址,请移步原文!!

浏览 56
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报