编写shell的时候经常遇见统计某一执行块消耗的时间,以下统计耗时转换成时:分:秒的方法。
#传入秒.纳秒 转换成 <时:分:秒.毫秒> 格式
function fun_use_hours(){
if [ $# -ne 2 ];then
echo $@
echo "usage: fun_use_hours <start_date> <end_date>"
echo " eg: fun_use_hours 1533274262 1533274263"
echo " start_date 开始时间"
echo " end_date 结束时间"
return 1
else
start=$1
end=$2
start_s=$(echo $start | cut -d '.' -f 1)
start_ns=$(echo $start | cut -d '.' -f 2)
end_s=$(echo $end | cut -d '.' -f 1)
end_ns=$(echo $end | cut -d '.' -f 2)
use_time=$(( ( 10#$end_s - 10#$start_s ) * 1000 + ( 10#$end_ns / 1000000 - 10#$start_ns / 1000000 ) ))
if [ $use_time -lt 1000 ];then #时间不足一秒钟
echo "0:0:0:${use_time}"
else
local hour=$(( ${use_time}/3600000 ))
local min=$(( (${use_time}-${hour}*3600000)/60000 ))
local sec=$(( (${use_time}-${hour}*3600000-${min}*60000)/1000 ))
local ms=$(( ${use_time}-${hour}*3600000-${min}*60000-${sec}*1000 ))
echo ${hour}:${min}:${sec}.${ms}
fi
return 0
fi
}
#程序执行入口 主函数
function main(){
##执行开始
local shell_start_date=`date +%s.%N`
##自己的执行任务
##...
#执行结束
local shell_end_date=`date +%s.%N`
use_time=`fun_use_hours ${shell_start_date} ${shell_end_date}`
echo "###############本次执行耗时${use_time}################################"
}
main