TehOne
October 24, 2009, 3:55pm
1
Hello,
I'm running a bash script and I'd like to get more accurate a runtime information then now.
So far I've been using this method:
STARTM=`date -u "+%s"`
.........
*script function....
.........
STOPM=`date -u "+%s"`
RUNTIMEM=`expr $STOPM - $STARTM`
if (($RUNTIMEM>59)); then
TTIMEM=`printf "%dm%ds\n" $((RUNTIMEM/60%60)) $((RUNTIMEM%60))`
else
TTIMEM=`printf "%ds\n" $((RUNTIMEM))`
fi
echo "Executing "script function" took: $TTIMEM"
However the script often runs under one second, so the result is 0s.
I'd like it display a more accurate runtime, best 0.015s or 1.123s and so on...
time {} is not really an option.. need the result as var as I pass it to another script...
Would this work perhaps (using GNU date)?:
res1=$(date +%s.%N)
sleep 1
res2=$(date +%s.%N)
echo "Start time: $res1"
echo "Stop time: $res2"
echo "Elapsed: $(( res2 - res1 ))"
$> ./test2
Start time: 1256415694.189522104
Stop time: 1256415695.193247576
Elapsed: 1.00372547202277929
TehOne
October 24, 2009, 4:23pm
3
scrutinizer:
Would this work perhaps (using GNU date)?:
res1=$(date +%Y%m%d%H%M%S.%N)
sleep 1
res2=$(date +%Y%m%d%H%M%S.%N)
echo "Start time: $res1"
echo "Stop time: $res2"
echo "Elapsed: $(( res2 - res1 ))"
$> ./test
Start time: 20091024220906.158808557
Stop time: 20091024220907.165223775
Elapsed: 1.00641441345214844
I've tested your code and I get this:
Start time: 20091024222112.280942000
Stop time: 20091024222113.284852000
./test: line 8: 20091024222113.284852000: syntax error in expression (error token is ".284852000")
Besides having the result 3 spots after comma would be nice too... and if the result is over 59 seconds then it has to be normal again 1m or 1m 20s and so on...
Ow that is right I tested it in ksh93. Bash can't deal with that.
Alternatively:
res1=$(date +%s.%N)
sleep 1
res2=$(date +%s.%N)
echo "Start time: $res1"
echo "Stop time: $res2"
echo "Elapsed: $(echo "$res2 - $res1"|bc )"
1 Like
TehOne
October 24, 2009, 4:32pm
5
scrutinizer:
Ow that is right I tested it in ksh93. Bash can't deal with that.
Alternatively:
res1=$(date +%s.%N)
sleep 1
res2=$(date +%s.%N)
echo "Start time: $res1"
echo "Stop time: $res2"
echo "Elapsed: $(echo "$res2 - $res1"|bc )"
Ok this time it works, what about the 3 spots (digits) after comma? And normal if higher then 59s ? Basically could you rewritte this into the form I posted in the beginning?
Too much precision, hey? Why don't you printf it into shape:
e.g.
printf "Elapsed: %.3F\n" $(echo "$res2 - $res1"|bc )
TehOne
October 24, 2009, 5:23pm
7
Works like a harm, thank you.