linux - 计算 shell 脚本每一步的时间并显示总执行时间

标签 linux bash shell unix scripting

我有下面的脚本,为了满足要求,我必须为每个脚本放置一些函数,以获取每个脚本的时间信息,并最终显示总时间。

我的主要脚本如下所示:

/u01/scripts/stop.sh ${1} | tee ${stop_log}    
/u01/scripts/kill_proc.sh ${1} | tee ${kill_log}    
/u01/scripts/detach.sh ${1}| tee ${detach_log}   
/u01/scripts/copy.sh ${1} | tee ${copy_log}   

我想使用类似下面的函数来获取每个脚本的执行时间,最后我可以使用一个全局变量来显示所有脚本所花费的总时间。

我在下面创建但不幸的是我无法正常使用,如果你有什么好心的帮助。

time_check()    
{         
  export time_log=${log}/time_log_${dts}.log          
  echo 'StartingTime:'date +%s > ${time_log}       
  echo 'EndingTime:'date +%s >> ${time_log}           
}          

我想使用类似于上面的函数来获取每个脚本的执行时间,最后使用一个全局变量我可以显示所有脚本所花费的总时间。任何人都可以指导如何获得所需的结果。

最佳答案

如果您不介意以秒为单位的时间粒度,您可以简单地这样做:

start=$SECONDS
/u01/scripts/stop.sh ${1} | tee ${stop_log}
stop=$SECONDS   
/u01/scripts/kill_proc.sh ${1} | tee ${kill_log}
kill_proc=$SECONDS   
/u01/scripts/detach.sh ${1}| tee ${detach_log}
detach=$SECONDS  
/u01/scripts/copy.sh ${1} | tee ${copy_log}
end=$SECONDS

printf "%s\n" "stop=$((stop-start)), kill_proc=$((kill_proc-stop)), detach=$((detach-kill_proc)), copy=$((end-detach)), total=$((end-start))"

您也可以编写一个函数来执行此操作:

time_it() {
  local start=$SECONDS rc
  echo "$(date): Starting $*"
  "$@"; rc=$?
  echo "$(date): Finished $*; elapsed = $((SECONDS-start)) seconds"
  return $rc
}

在 Bash 版本 >= 4.2 中,您可以使用 printf 打印日期而不是调用外部命令:

time_it() {
  local start=$SECONDS ts rc
  printf -v ts '%(%Y-%m-%d_%H:%M:%S)T' -1
  printf '%s\n' "$ts Starting $*"
  "$@"; rc=$?
  printf -v ts '%(%Y-%m-%d_%H:%M:%S)T' -1
  printf '%s\n' "$ts Finished $*; elapsed = $((SECONDS-start)) seconds"
  return $rc
}

并将其调用为:

start=$SECONDS
time_it /u01/scripts/stop.sh ${1} | tee ${stop_log}    
time_it /u01/scripts/kill_proc.sh ${1} | tee ${kill_log}    
time_it /u01/scripts/detach.sh ${1}| tee ${detach_log}   
time_it /u01/scripts/copy.sh ${1} | tee ${copy_log}
echo "Total time = $((SECONDS-start)) seconds"

相关:

关于linux - 计算 shell 脚本每一步的时间并显示总执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51801292/

相关文章:

linux - 如何计算目录中的文件数并在 if 语句中进行测试?

bash - Unix shell 之间的可移植性——我对这个问题的思考是否正确?

Linux 相当于 OS X 的/usr/bin/open

shell - Jenkins 文件 : permission denied when running sh step in Docker container

linux - bash 中的 grep 语句

linux - 如何在 sed 中用另一个字符替换单引号?

linux - 列出文件夹但如果文件夹与 Bash 中的列表匹配则排除

linux - 作为内置驱动程序构建时,驱动程序不工作

arrays - bash printf 两列中的两个数组

php - 在 bash 中生成 php 类