我在互联网上环顾四周,想知道是否已经有办法对一个可执行文件/脚本的某个部分进行计时,看看这个部分需要多长时间,但我发现的更多的是文件之外的部分。因此,我想输入一个行,它启动一个计时器,在这个部分的末尾,停止计时器,并向我显示经过的时间,不是整个事情,而是一个部分。示例:
#!/bin/sh
IPTABLES="/sbin/iptables"
BLOCKEDIPS_XS=/root/iptables/iptables/blockxs.zone
$IPTABLES -F
$IPTABLES -F INPUT
$IPTABLES -F OUTPUT
$IPTABLES --delete-chain
$IPTABLES -F FORWARD
$IPTABLES -F -t mangle
$IPTABLES -F -t nat
$IPTABLES -X
timer start
/bin/egrep -v "^#|^$" $BLOCKEDIPS_XS | while IFS= read -r ip
do
# Append everything to droplist
$IPTABLES -A droplist -i eth0 -s $ip -j LOG --log-prefix " Drop IP List blockxs "
$IPTABLES -A droplist -i eth0 -s $ip -j DROP
done <"$BLOCKEDIPS_XS"
timer stops, shows elapsed time发布于 2018-05-16 13:49:48
在命令组和SECONDS变量上操作的D1都是bash特性,而不是sh中的。使用sh,您可以使用date命令在两个点获得时间戳,然后得到差异。从那个时代开始,date +%s将在几秒钟内给出时间。
# timer start
start=$(date +%s)
/bin/egrep -v "^#|^$" $BLOCKEDIPS_XS | while IFS= read -r ip
do
# Append everything to droplist
$IPTABLES -A droplist -i eth0 -s $ip -j LOG --log-prefix " Drop IP List blockxs "
$IPTABLES -A droplist -i eth0 -s $ip -j DROP
done <"$BLOCKEDIPS_XS"
# timer stops, shows elapsed time
echo $(( $(date +%s) - start ))发布于 2018-05-16 11:04:11
您可以使用命令分组对bash脚本的一部分进行计时。
#!/bin/bash
echo "foo"
sleep 1
time {
sleep 2
echo "bar"
sleep 3
}
sleep 1
echo "baz"例如。
$ ./somescript.sh
foo
bar
real 0m5.006s
user 0m0.005s
sys 0m0.001s
baz使用子should进行分组(即用括号代替大括号)也应该有效。
发布于 2018-05-16 10:44:20
最简单的方法是将time命令放在正在运行的命令前面。例如:
$ time locate display-auto
/etc/cron.d/display-auto-brightness
/home/rick/Downloads/display-auto-brightness
/home/rick/Pictures/display-auto-brightness conky.png
/home/rick/Pictures/display-auto-brightness systray.png
/home/rick/Pictures/display-auto-brightness-config 1.png
/home/rick/Pictures/ps display-auto-brightness.png
/lib/systemd/system-sleep/display-auto-brightness
/mnt/e/etc/cron.d/display-auto-brightness
/mnt/e/lib/systemd/system-sleep/display-auto-brightness
/mnt/e/usr/local/bin/display-auto-brightness
/usr/local/bin/display-auto-brightness
real 0m0.826s
user 0m0.803s
sys 0m0.016s我们使用locate命令查找名称中包含display-auto的所有文件名。只需在命令前面插入time命令即可。
的时间
您可以在脚本中使用$SECONDS变量来获取其中一部分的时间。例如:
SECONDS=0
/bin/egrep -v "^#|^$" $BLOCKEDIPS_XS | while IFS= read -r ip
do
# Append everything to droplist
$IPTABLES -A droplist -i eth0 -s $ip -j LOG --log-prefix " Drop IP List blockxs "
$IPTABLES -A droplist -i eth0 -s $ip -j DROP
done <"$BLOCKEDIPS_XS"
timer stops, shows elapsed time
BlockTime=$SECONDS
echo "Total time to block IPs: $BlockTime Seconds"在此代码中,SECONDS被重置为零,然后在发生冗长的过程后获得。
https://askubuntu.com/questions/1036876
复制相似问题