一. 秒级别
#!/bin/bash
start_time=`date --date='0 days ago' "+%Y-%m-%d %H:%M:%S"`
#this is your shell script
sleep 1
##############
finish_time=`date --date='0 days ago' "+%Y-%m-%d %H:%M:%S"`
duration=$(($(($(date +%s -d "$finish_time")-$(date +%s -d "$start_time")))))
echo "this shell script execution duration: $duration"
执行如下命令:
chmod +x time_s.sh
./time_s.sh
结果:
二.毫秒级别
#!/bin/bash
function timediff() {
# time format:date +"%s.%N", such as 1502758855.907197692
start_time=$1
end_time=$2
start_s=${start_time%.*}
start_nanos=${start_time#*.}
end_s=${end_time%.*}
end_nanos=${end_time#*.}
# end_nanos > start_nanos?
# Another way, the time part may start with 0, which means
# it will be regarded as oct format, use "10#" to ensure
# calculateing with decimal
if [ "$end_nanos" -lt "$start_nanos" ];then
end_s=$(( 10#$end_s - 1 ))
end_nanos=$(( 10#$end_nanos + 10**9 ))
fi
# get timediff
time=$(( 10#$end_s - 10#$start_s )).`printf "%03dn" $(( (10#$end_nanos - 10#$start_nanos)/10**6 ))`
echo $time
}
start=$(date +"%s.%N")
# Now exec some command
sleep 1.2563
end=$(date +"%s.%N")
# here give the values
#start=1502758855.907197692
#end=1502758865.066894173
timediff $start $end
执行如下命令:
chmod +x time_s.sh
./time_ms.sh
结果:
参考:
https://blog.csdn.net/u010339879/article/details/75949076
https://www.lagou.com/lgeduarticle/2266.html
https://blog.csdn.net/weixin_34050427/article/details/85934782