统计Shell脚本执行时间,帮助分析改进脚本执行

  1. 用 date 相减
#!/bin/bash

startTime=`date +%Y%m%d-%H:%M:%S`
startTime_s=`date +%s`

endTime=`date +%Y%m%d-%H:%M:%S`
endTime_s=`date +%s`

sumTime=$[ $endTime_s - $startTime_s ]

echo "$startTime ---> $endTime" "Total:$sumTime seconds"

  1. 用 time 工具
time sh xxx.sh
# 会返回3个时间数据
# real 该命令的总耗时, 包括user和sys及io等待, 时间片切换等待等等
# user 该命令在用户模式下的CPU耗时,也就是内核外的CPU耗时,不含IO等待这些时间
# sys 该命令在内核中的CPU耗时,不含IO,时间片切换耗时.

​javascript:void(0)​​ 

原文链接:​​javascript:void(0)​

在shell脚本中统计程序执行完毕所需要的时间不像在java中使用System.currentTimeMillis()方便

稍微记录一下,以供备用,免得又去花时间想(统计程序执行消耗多少s):

starttime=`date +'%Y-%m-%d %H:%M:%S'` #执行程序 endtime=`date +'%Y-%m-%d %H:%M:%S'` start_seconds=$(date --date="$starttime" +%s); end_seconds=$(date --date="$endtime" +%s); echo "本次运行时间: "$((end_seconds-start_seconds))"s"



Sleep


在有的shell(比如linux中的bash)中sleep还支持睡眠(分,小时)
sleep 1 睡眠1秒
sleep 1s 睡眠1秒
sleep 1m 睡眠1分
sleep 1h 睡眠1小时



shell 浮点数运算

shell计算中使用除法,基本默认上都是整除。
比如:
num1=2
num2=3
num3=`expr $num1 / $num2`1

这个时候num3=0 ,是因为是因为expr不支持浮点除法
解决的方法:
num3=`echo "scale=2; $num1/$num2" | bc`1
使用bc工具,sclae控制小数点后保留几位
还有一种方法
awk 'BEGIN{printf "%.2f\n",’$num1‘/’$num2‘}'1
如果用百分比表示
awk 'BEGIN{printf "%.2f%\n",(’$num1‘/’$num2‘)*100}

(另外:代码中的 [] 执行基本的算数运算,如:

#!/bin/bash a=5 b=6 result=$[a+b] # 注意等号两边不能有空格 echo "result 为: $result" )