像秒表一样实时计算每个命令所花费的时间

像秒表一样实时计算每个命令所花费的时间

我有一个脚本可以做很多事情,例如:

echo -e " finding mp3 files"
find / *.mp3
Elapsed time: 0

假设这需要 10 秒。

将它们复制到某个位置的函数(这只是一个示例,不是我的实际脚本):

echo copying files;
cp *.mp3 /
elapsed time: 6

我需要一种方法来计算和显示运行时钟,同时find查找所有文件,然后在复制cp文件时重置并显示新的运行时钟。

我试过这个:

Timing () {
SECONDS=0; while true do;
printf '\e[1;96mElapsed Time: %dm:%ds\e[0m\n' $(($SECONDS%3600/60)) $(($SECONDS%60))
done &
}

然后在执行命令时调用该函数。

但是,我无法重置时间,也无法退出此后台while循环。

这是我想要添加计时功能的完整脚本:

#!/bin/bash

#--------------------------------------------------------------------------------#
#                  Modify to Match your Environment                              #
#--------------------------------------------------------------------------------#

#enter managed servers names  STARTING ORDER  seperated by 'space'
#COMPNENTS Y or N in CAPS litters 

MANAGED_SERVERS_NAMES="WLS_FORMS WLS_REPORTS"
NODEMANAGER_SCRIPT_LOCATION="$WLS_HOME"/server/bin/startNodeManager.sh 
DOMAIN_ENV_LOCATION="$DOMAIN_HOME"/bin/setDomainEnv.sh
ADMINSERVER_SCRIPT_LOCATION="$DOMAIN_HOME"/bin/startWebLogic.sh
MANAGED_SERVERS_SCRIP_LOCATION="$DOMAIN_HOME"/bin/startManagedWebLogic.sh
OPMNCTL_COMPONENTS=Y
EMCTL_COMPONENT=Y


################################################################################
#--------------------------------------------------------------------------------#
#           This Script Is A CopyRight To KhaLiD Abo EL MaGd                     #
#                  Don't Modify Any Thing in This Section                        #
#                                                                                #
#--------------------------------------------------------------------------------#
set -e
clear
TFILE=starting.log
debug=$1
if [[ -n "$debug" ]]; then
cat /dev/null > ${TFILE}
gnome-terminal  -e  "tail -F $TFILE" &
fi

Check_Status_NM ()
{
tail -f ${TFILE} | while read LOGLINE
do
    if [[ "${LOGLINE}" == *"Secure socket listener started on port"* ]] 
    then
    echo -e "\e[92mNodeManager Started\e[0m"
    pkill -P $$ tail
    break
    elif [[ "${LOGLINE}" == *"Address already in use"*  ]]; then
    pkill -P $$ tail
    echo -e "Cannot Start NodeManager\nSee ${TFILE} for more info\n "
  printf '\e[1;96mElapsed Time: %dm:%ds\e[0m\n' $(($SECONDS%3600/60)) $(($SECONDS%60))
  echo ""
  echo "$SECONDS" > time
    exit 1
    nohup kill -9 `ps -ef | grep ${TFILE} | awk '{print $2}'`  > /dev/null 2>&1 &
    echo "Total Time: $(cat time |   paste -sd+ |  bc)s"
    rm -rf time
    fi
done
}
#----------------------------------------------------------------
Check_Status ()
{
sleep 2
tail -F ${TFILE} | while read LOGLINE
do
  if [[ "${LOGLINE}" == *"<Server state changed to STANDBY>"* ]]; then
    echo -e "\e[94mServer state changed to STANDBY\e[0m"
  elif  [[ "${LOGLINE}" == *"<Server state changed to >"* ]]; then
      echo -e "\e[94mServer state changed to ADMIN\e[0m"
  elif [[ "${LOGLINE}" == *"<Server state changed to RESUMING>"* ]]; then
     echo -e "\e[94mServer state changed to RESUMING\e[0m"
  elif  [[ "${LOGLINE}" == *"<Server state changed to STARTING>"* ]]; then
      echo -e "\e[94mServer state changed to STARTING\e[0m"


    elif [[ "${LOGLINE}" == *"The Network Adapter could not establish the connection"* ]] ; then
    echo -e "\e[5m\e[93mWARNING\e[0m Could not establish the connection\n\e[91mCheck Connection to Database\e[0m"
   elif  [[ "${LOGLINE}" == *"<Server state changed to STARTING>"* ]]; then
      echo -e "\e[94mServer state changed to RUNNING\e[0m"
    elif [[ "${LOGLINE}" == *"<Server started in RUNNING mode>"* ]] || [[ "${LOGLINE}" == *"<Demo trusted CA certificate is being used in production mode:"* ]];then
    echo -e "\e[92mServer Started\e[0m"
      pkill -P $$ tail
    cat /dev/null > ${TFILE}
    break
    elif [[ "${LOGLINE}" == *"<Server state changed to FORCE_SHUTTING_DOWN>"* ]]; then
      pkill -P $$ tail
     echo -e "\e[91mCannot Start Server\e[0m\nSee ${TFILE} for more info\n"
    printf '\e[1;96mElapsed Time: %dm:%ds\e[0m\n' $(($SECONDS%3600/60)) $(($SECONDS%60))
    echo ""
   echo "$SECONDS" >> time
    nohup kill -9 `ps -ef | grep ${TFILE} | awk '{print $2}'`  > /dev/null 2>&1 &
    echo "Total Time: $(cat time |   paste -sd+ |  bc)s"
    rm -rf time
    exit 1
    fi
done
}
#---------------------------------------------------------------------------------------
#Start NodeManager:
SECONDS=0
echo -e "Starting NodeManager..."
nohup "$NODEMANAGER_SCRIPT_LOCATION"  > ${TFILE}  2>&1 &
 Timing ******************
Check_Status_NM
printf '\e[1;96mElapsed Time: %dm:%ds\e[0m\n' $(($SECONDS%3600/60)) $(($SECONDS%60))
echo ""
echo "$SECONDS" >> time
#Start WebLogic AdminServer------------------------------------------------
SECONDS=0
echo -e "Starting AdminServer..." 
nohup "$DOMAIN_ENV_LOCATION" > ${TFILE}   2> /dev/null &
 Timing ********************
nohup  > ${TFILE} "$ADMINSERVER_SCRIPT_LOCATION"  2> /dev/null &
Check_Status
printf '\e[1;96mElapsed Time: %dm:%ds\e[0m\n' $(($SECONDS%3600/60)) $(($SECONDS%60))
echo ""
echo "$SECONDS" >> time
#----------- MANAGED SERVERS------------------------------
for i in ${MANAGED_SERVERS_NAMES}
do
SECONDS=0
echo "Starting $i Server..."
nohup ${MANAGED_SERVERS_SCRIP_LOCATION} $i  > ${TFILE}  2> /dev/null &
Check_Status
printf '\e[1;96mElapsed Time: %dm:%ds\e[0m\n' $(($SECONDS%3600/60)) $(($SECONDS%60))
echo ""
echo "$SECONDS" >> time
done
nohup kill -9 `ps -ef | grep ${TFILE} | awk '{print $2}'`  > /dev/null 2>&1 &

#--------------------- OPMNCTL------------------------
if [[ "${OPMNCTL_COMPONENTS}" == *"Y"* ]]; then
SECONDS=0
echo -e "Starting opmn components"
nohup opmnctl startall > /dev/null 2>&1 &
sleep 2
if ( opmnctl status |grep --quiet Init); then
echo -e "\e[94mWaiting For opmn components to Start\e[0m"
opmnctl status |grep -v --quiet Init
opm_pid=$!
while [ -d /proc/$opm_pid ]; do
    echo -n "."
    sleep 2
done
else
echo -e "\e[92mStarted\e[0m" 
fi
opmnctl status | grep -v Alive
printf '\e[1;96mElapsed Time: %dm:%ds\e[0m\n' $(($SECONDS%3600/60)) $(($SECONDS%60))
echo ""
echo "$SECONDS" >> time
fi
#---------------------EMCTL-----------------------------------
if [[ "${EMCTL_COMPONENT}" == *"Y"* ]]; then
SECONDS=0
emctl start agent
printf '\e[1;96mElapsed Time: %dm:%ds\e[0m\n' $(($SECONDS%3600/60)) $(($SECONDS%60))
echo ""
echo "$SECONDS" >> time
fi
#-----------------------------------------------------------
TIMEE=$(cat time |   paste -sd+ |  bc)
echo ""
printf '\e[1;96mTotal Time: %dm:%ds\e[0m\n'  $(($TIMEE%3600/60)) $(($TIMEE%60))
cat /dev/null > time
exit 0

通过根据答案执行此操作,我基本上能够得到我想要的东西,但我想知道如何在打印服务器已启动或无法启动服务器后终止 Check_Status 函数中的 while 循环

echo -e "Starting AdminServer..." 
nohup "$DOMAIN_ENV_LOCATION" > ${TFILE}   2> /dev/null &
START_TIME=$(date +%s)
nohup  > ${TFILE} "$ADMINSERVER_SCRIPT_LOCATION"  2> /dev/null &
Check_Status &
while [[ -d /proc/$! ]]; do
SECONDS=$(( $(date +%s)-START_TIME ))
 printf "\e[1;96mElapsed Time: %02dm:%02ds\e[0m\r" $(($SECONDS%3600/60))     $(($SECONDS%60))
done
printf "\e[1;96mElapsed Time: %dm:%ds\e[0m\n" $(($SECONDS%3600/60))    $(($SECONDS%60))
echo "$SECONDS" >> time

答案1

这显示了完成的时间:

#! /bin/bash
START_TIME=$(date +%s)
echo -n Finding mp3 files
sleep 3 # some time consuming command
echo .\ Elapsed time: $(( $(date +%s)-START_TIME ))

它会回应:

Finding mp3 files

进而

Finding mp3 files. Elapsed time: 3

如果您想在等待时看到时间计数,那么耗时的命令一定不能回显任何内容(当然)。

#! /bin/bash
START_TIME=$( date +%s )
echo Finding mp3 files
sleep 3 & # some time consuming command
while [[ -d /proc/$! ]]; do
    echo -en \\rElapsed time: $(( $(date +%s)-START_TIME ))
    sleep 0.1
done
echo .

说明:当该命令进入后台时,&它会将进程 ID 号保留在$!.此过程由 中的(虚拟)目录表示/proc/$!。只要这个目录存在,命令就会运行,我们就会计算时间。


第三个例子;更像是这个问题。替换sleep 3为耗时的命令。

#! /bin/bash
echo "Starting NodeManager..."
START_TIME=$(date +%s)
nohup sleep 3 &
while ps -p $! > /dev/null ; do
    SECONDS=$(( $(date +%s)-START_TIME ))
    printf "\r\e[1;96mElapsed Time: %02dm:%02ds\e[0m" $(($SECONDS%3600/60)) $(($SECONDS%60))
done
Echo

编辑:第三个例子现在显示正确的方式测试进程是否仍在运行。 (但它必须启动一个进程ps,因此速度较慢 - 您的选择)

答案2

您可以使用pv

sleep 10 | pv -t

find / -name '*.mp3' | pv -t

pv是一个类似的传递cat(有时甚至更有效,因为它splice()在可能的情况下使用系统调用),将计时信息写入 stderr。

Elapsed time:如果你也想显示:

pv -N 'Elapsed time' -t

或(使用较新版本):

pv -F 'Elapsed time: %t'

如果使用zshkshbash,您可能希望设置该pipefail选项以不丢失正在监视的命令的退出状态:

timewatch() (
  set -o pipefail
  "$@" | pv -tN 'Elapsed time'
)

timewatch find / -name '*.mp3' || handle_error

相关内容