Playing with time
To calculate how long specific programs/scripts take you can use time.
Because time runs differently when you use the full path /usr/bin/time (external program) or time (bash builtin) the job gets a bit nasty.
I need to use the builtin because if I use the /usr/bin/time it won`t understant the tons of functions I have loaded on the bash shell.
Well, here is how I was using it
=========================================================
COMMANDTORUN="YOURCODE";
# This allows me to see the output and get the time in different places (output and file)
(time YOURCODE) 2> /tmp/timeXtimeTLS.txt ;
TIMECOMMAND=`egrep "^real" /tmp/timeXtimeTLS.txt`;
# Log results
echo "[`/bin/date +"%F %R"`] Command - $COMMANDTORUN - took - $TIMECOMMAND -" >> filelog ;
=========================================================
But then I found in http://www.askdavetaylor.com/how_can_i_time_portions_of_a_linux_shell_script.html
a better way to do it
timey () {
before=$(date +%s)
echo "Started : $(date)"
# commands to time go here
"$@"
after=$(date +%s)
elapsed_seconds=$(expr $after - $before)
echo "Ended : $(date)"
echo "Elapsed time : $(date -d "1970-01-01 $elapsed_seconds sec" +%H:%M:%S)"
}
=========================================================
And on http://www.linuxforums.org/forum/linux-programming-scripting/108351-how-grab-timed-duration-command-save-variable.html
another way. Just seconds, but with decimals.
timex () {
begin_time=$(date +%s.%N)
# commands to time go here
"$@"
end_time=$(date +%s.%N)
echo "$end_time - $begin_time" | bc
}
To which you could add
echo "[`/bin/date +"%F %R"`] Command: $@ - took: `echo "$end_time - $begin_time" | bc` sec -" >> time.log
Then using awk you can calculate total time used in the log
TOTAL=`egrep -o "took:.*" time.log | egrep -o "[0-9]*\.[0-9]" | awk '{ SUM += $1} END { print SUM }'`
And display it nicely (this is the easiest way I have found to display any amount of seconds on the format hours minutes seconds)
date -d "1970-01-01 $TOTAL sec" +%H:%M:%S
Hope it helps :o)
0 Comments:
Post a Comment
<< Home