Link to home
Start Free TrialLog in
Avatar of hankknight
hankknightFlag for Canada

asked on

Linux: execution time to 1000th of a second

#!/bin/bash
t1=$( date +"%s" )
sleep 1.23
t2=$( date +"%s" )
DIFF=$(( $t2 - $t1 ))
echo "Exicution time: $DIFF seconds"

Open in new window

I want the results to be like
1.234 seconds
Avatar of jb1dev
jb1dev

You need to add %N to your date format for nanoseconds and you need to use bc for floating point evaluation rather than just expr "-"

#!/bin/bash
t1=$( date +"%s.%N" )
sleep 1.23
t2=$( date +"%s.%N" )
echo "$t2 - $t1"
DIFF=$(echo "($t2 - $t1) * 1000" | bc)
echo "Execution time: $DIFF seconds"

Open in new window


See also
<Link removed by woolmilkporc, EE TA>
Sorry that *1000 is incorrect.

That should be

#!/bin/bash
t1=$( date "+%s.%N" )
sleep 1.23
t2=$( date "+%s.%N" )
echo "$t2 - $t1"
DIFF=$(echo "( $t2 - $t1 )" | bc)
echo "Exicution time: $DIFF seconds"

Open in new window


You can then add scale to bc to limit this to 3 digits. (or however many.)
ASKER CERTIFIED SOLUTION
Avatar of jb1dev
jb1dev

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@woolmilkporc
Sorry about that. I have not been posting here in a while.
I was not aware of this rule.