[英]How to time a bunch of things in a bash script
我想编写一个脚本来运行具有不同参数的脚本/服务(来自服务的卷曲)。 现在,我想为每个查询计时并将其存储在文件中? 我怎样才能做到这一点?
#! /bin/bash
input="/home/ubuntu/flowers"
while IFS= read -r line
do
time myservice 'get?flower="$line"'
done < "$input"
我也试过:
cat flowers | xargs -I {} time myservice "get?flower={}" | jq -c '.[] | {flower}'
我的 output 看起来像
/usr/local/lib/python2.7/dist-packages/gevent/builtins.py:96: CryptographyDeprecationWarning: Python 2 is no longer supported by the Python core team. Support for it is now deprecated in cryptography, and will be removed in the next release.
result = _import(*args, **kwargs)
{"flower":"daffodil"}
{"flower":"daffodil"}
{"flower":"daffodil"}
{"flower":"daffodil"}
0.47user 0.07system 0:10.49elapsed 5%CPU (0avgtext+0avgdata 65432maxresident)k
或包含类似的东西
Myservice 10.#.#.#:7092 returned bad json for get?flower=lilly
Myservice 10.#.#.#:7092 returned bad json for get?flower=lilly
Myservice 10.#.#.#:7092 returned bad json for get?flower=lilly
Failed to connect (or too slow) on 10.#.#.#2:7092 timed out
Timeout Error: ('10.#.#.#', 7092)
Failed to connect (or too slow) on 10.#.#.#:7092
Timeout Error: ('10.#.#.#', 7092)
Failed to connect (or too slow) on 10.#.#.#:7092
Timeout Error: ('10.#.#.#', 7092)
我想跳过。
我知道如果没有简单的方法,我可以稍后进行清理。
我想要一个类似的文件
lilly 0.91
hibiscus 0.93
其中数字是用户端的时间。
如果您要查找的只是每个查询所花费的时间,并且您不关心myservice
中的 output,那么您可以将其重定向到 /dev/null 并忽略它。
测量时间有点棘手。 您不能将 output 从time
命令重定向到与其运行的命令不同的位置。 所以最好使用其他方法。 Bash 有一个内部变量“SECONDS”,可用于测量经过的时间,但我认为您需要比这更细的粒度。 所以你应该改用'date'命令。
您还需要使用bc
(或类似的)来进行浮点运算。
此外,如果myservice
命令正确处理故障(即在故障时返回非零值),那么您也可以干净利落地处理故障。
#!/bin/bash
input_file="/home/ubuntu/flowers"
while IFS= read -r line; do
start_time=$(date +%s.%N) #
myservice 'get?flower="$line"' > /dev/null 2>&1
return_value=$?
end_time=$(date +%s.%N)
elapsed_time=$(echo "scale=3; ${end_time} - ${start_time}" | bc)
if [ ${return_value} -eq 0 ]; then
echo "${line}: ${elapsed_time}"
else
echo "${line}: Failed"
fi
done < "${input_file}"
date
命令中的%s.%3N
格式字符串表示:
%s
秒.
这 '。' 特点%N
纳秒 bc
命令的scale=3
输入告诉它 output 3 个小数位。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.