Calculate time of shell script execution

When we use shell scripts to carry out some batch activities, in some scenarios, we need to know how long the script execution took. When it comes to this topic, our general idea is to record the time and then start the stage. It is possible to record the time and then calculate the time difference, but it is troublesome to convert the format. Today we use a simple method.
script content to execute

#!/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.."

Note that we started to define a variable started and use the global variable $SECONDS to assign a value.
This global variable records the current time at all times and does not require us to use commands to obtain it. That is to say, the system has a clock that goes by default, and we only need to calculate it once and it is OK.
After the execution is completed, use the current clock to subtract the recorded clock and it will be OK. Note that the unit is seconds;
note that there are precautions when using this method to execute the script, as follows:
1. Ordinary method execution.

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. The correct method
is to use time bash to add the script name, as follows

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

Guess you like

Origin blog.csdn.net/mainmaster/article/details/132065297