计算shell脚本执行的时间

我们在使用shell脚本进行一些批量活动的时候,在有的场景下会需要知道脚本执行用了多长的时间,一谈到这个话题,我们一般的想法就是记录时间再开始阶段,执行完成后再记录时间,然后求时间差,这样是可以的,但是要进行格式的转换,比较麻烦,今天我们使用一个简单的方法。
要执行的脚本内容

#!/bin/sh
started=$SECONDS
#清除缓存
#sh -c "sync && echo 3 > /proc/sys/vm/drop_caches"
dd if=/dev/zero of=/home/forlinx/test/test.bin bs=64k count=1000 conv=fsync oflag=direct
if [ $? -eq 0 ]
then 
        echo "emmc write $i succesful " | tee -a ./result.log
else
        echo "emmc write $i failure " | tee -a ./result.log
fi
sleep 2s
echo "" 
#dd if=/dev/zero of=$a bs=16k count=1000 conv=sync iflag=direct
#sh -c "sync && echo 3 > /proc/sys/vm/drop_caches"
dd if=/home/forlinx/test/test.bin of=/dev/null  bs=64k count=1000 conv=sync iflag=direct
if [ $? -eq 0 ]
then
        echo "emmc read $i succesful " | tee -a ./result.log
else
        echo "emmc read $i failure " | tee -a ./result.log
fi
sleep 2s
echo "" 
echo "runtimes = $(($SECONDS-$started)) seconds.."

注意看,我们再开始定义了一个变量started使用全局变量$SECONDS来赋值。
这个全局变量是时刻记录当前的时间的而不用我们使用命令来获取,就是说,系统默认就有一个时刻走的时钟,我们仅需要计算一次就OK了。
执行完成后,使用当前的时钟减去我们记录的时钟就OK了,注意单位是秒;
注意,使用这个方法需要再执行脚本的时候有注意事项,如下:
1.普通方法执行。

forlinx@ubuntu:~/test$ ./emmc.sh 
1000+0 records in
1000+0 records out
65536000 bytes (66 MB, 62 MiB) copied, 0.0855573 s, 766 MB/s
emmc write  succesful 

1000+0 records in
1000+0 records out
65536000 bytes (66 MB, 62 MiB) copied, 0.0765326 s, 856 MB/s
emmc read  succesful 

./emmc.sh: 25: ./emmc.sh: arithmetic expression: expecting primary: "-"

2.正确方法
使用time bash 加脚本名称,如下

forlinx@ubuntu:~/test$ time bash emmc.sh 
1000+0 records in
1000+0 records out
65536000 bytes (66 MB, 62 MiB) copied, 0.107433 s, 610 MB/s
emmc write  succesful 

1000+0 records in
1000+0 records out
65536000 bytes (66 MB, 62 MiB) copied, 0.0898149 s, 730 MB/s
emmc read  succesful 

runtimes = 4 seconds..

real	0m4.207s
user	0m0.006s
sys	0m0.137s

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

six2me

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值