我使用下面的脚本来获得一个特定网站的平均响应时间。它运行得很好。我只需要转换响应中的一些值,比如time_total,我想以毫秒为单位查看它,而size_download则以KB为格式。在命令的最后,我分享了平均响应时间。我也想打印它在毫秒。任何帮助是真的感谢。
for ((i=1;i<=50;i++)); do curl -w 'Return Code: %{http_code}; Bytes Received: %{size_download}; Response Time: %{time_total}\n' "https://www.google.com" -m 2 -o /dev/null -s; done |tee /dev/tty|awk '{ sum += $NF; n++ } END { If (n > 0); print "Average Response Time =",sum /n;}'
2条答案
按热度按时间4dc9hkyq1#
Three answer here...
As this question is tagged shell (not bash), here is three different way for doing this, by using
awk
+bash
,shell
+bc
orbash
alone.1. Using
awk
to process output and compute averagesAs doing forks like
curl ... | awk ...
repetitively, is resource killer, I prefer to runawk
only once, doing the whole formatting output job underawk
:May produce:
2. Working on averages using shell
As shell don't work with floating numbers, you have to use
bc
or another subprocess to resolv this operations.As doing forks like
var=$(echo '3*4'|bc)
is resource killer, I prefer to runbc
only once, as a background process. One advantage of this isbc
can store overall variables (total download
andtotal size
here).First part: Init some variables and run
bc
Creating two fifos for backgrounded
bc
and one fifo forcurl
, making parsing of curl's output easier.Declaring some variables, and
numfmt
function intobc
for further use...Note about
numfmt
: This function compute human readable presentation from integer value, output two valuesoctal character
octal value ofb
,K
,M
,G
,P
andT
andfloating number
from submited value, divided by power of 1024The character from octal could be output by
printf '%b' \\$value
under shell.# read variables from curl
# Last part:
main
routine
Run sample:
3. Last: bash
This question is tagged sh , but
for ((i=...
syntax is a bashism. So here is a compact pure bash version of this:Without any fork to
bc
norawk
, all operation are done in pseudo float using shifted integers.This will produce same result:
1sbrub3j2#
您可以通过
awk
传输curl输出,并根据需要对其进行格式化,如下所示:因此,一行代码如下:
您也可以根据需要设置数字的格式,方法是将g,例如%.2f表示2位小数精度,%d表示整数...