计算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

猜你喜欢

转载自blog.csdn.net/mainmaster/article/details/132065297