当前位置: 首页 > 科技观察

使用curl命令分析请求耗时情况

时间:2023-03-15 11:43:24 科技观察

最近在工作中遇到了一个问题。某个请求的响应很慢,所以希望有一种方法可以分析请求是哪一步耗时比较长,以便进一步找到问题的原因。在网上搜索后,发现了一个非常有用的方法。curl命令可以帮助你分析请求的各个部分的耗时。curl命令提供了-w参数,这个参数在manpage是这样解释的:-w,--write-outMakecurldisplayinformationonstdoutafteracompletedtransfer.Theformatisastringthatmaycontainplaintextmixedwithanynumberofvariables.Theformatcanbespecifiedasaliteral"string",oryoucanhavecurlreadtheformatfromafilewith"@filename"andtotellcurltoreadtheformatfromstdinyouwrite"@-".Thevariablespresentintheoutputformatwillbesubstitutedbythevalueortextthatcurlthinksfit,asdescribedbelow.Allvariablesarespecifiedas%{vari‐able_name}andtooutputanormal%youjustwritethemas%%。你可以通过使用\n输出一个换行符,一个回车符与\randatabspace与\t。它可以按照指定的格式打印一些信息,可以使用一些特定的变量,支持\n、\t和\r转义字符。提供的变量很多,比如status_code、local_port、size_download等,本文只关注与请求时间相关的变量(time_开头的变量)。首先将以下内容写入文本文件curl-format.txt:?~catcurl-format.txttime_namelookup:%{time_namelookup}\ntime_connect:%{time_connect}\ntime_appconnect:%{time_appconnect}\ntime_redirect:%{time_redirect}\ntime_pretransfer:%{time_pretransfer}\ntime_starttransfer:%{time_starttransfer}\n--------\ntime_total:%{time_total}\n那么这些变量是什么意思呢?解释一下:time_namelookup:DNS域名解析时,就是把https://zhihu.com转换成ip地址的过程time_connect:TCP连接建立的时间,也就是三次握手的时间time_appconnect:SSL/SSH等上层协议建立连接的时间,如connect/handshake时间time_redirect:从开始到最后一次请求事务的时间time_pretransfer:从请求开始到开始响应time_starttransfer:从请求开始到传输完最后一个字节的时间time_total:本次请求花费的总时间我们来看一个简单的请求,没有重定向,也没有SSL协议计时:?~curl-w"@curl-format.txt"-o/dev/null-s-L"http://cizixs.com"time_namelookup:0.012time_connect:0.227time_appconnect:0.000time_redirect:0.000time_pretransfer:0.227time_starttransfer:0.443----------time_total:0.867可以看到打印出这个请求每一步的时间,每个数字的单位是秒(seconds),所以可以分析哪一步比较耗时,方便定位问题,这个命令各个参数的含义:-w:从文件中读取要打印信息的格式-o/dev/null:丢弃内容response,因为这里我们不关心它,只关心request-s的耗时:不打印进度条从这个输出我们可以计算出每一步的时间:DNS查询:12msTCP连接时间:pretransfter(227)-namelookup(12)=215ms服务器处理时间:starttransfer(443)-pretransfer(227)=216ms内容传输时间:total(867)-starttransfer(443)=424ms这是一个更复杂的时间,请访问某个主页,中间有重定向和SSL协议:?~curl-w"@curl-format.txt"-o/dev/null-s-L"https://baidu.com"time_namelookup:0.012time_connect:0.018time_appconnect:0.328time_redirect:0.356time_pretransfer:0.018time_starttransfer:0.027----------time_total:0.384可以看到time_appconnect和time_redirect不为0,SSL协议处理时间为328-18=310ms。并且缩短了pretransfer和starttransfer的时间,也就是重定向后request的时间。