shell统计任务执行时长

编写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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值