Twitter

Some bash tips -- 17 -- SECONDS

Reinventing the wheel is rooted deep inside our DNA. I really try to never reinvent the wheel but I recently got caught (!).

Indeed, when I wanted to know how fast / how slow something was running or just to log the time spent by a script running, I used to write it like that:
start=$(date +%s)                                          <== Epoch seconds
do_something                                               <== Something is running
end=$(date +%s)                                            <== Epoch seconds
echo "Time spent: $(( end-start )) seconds"                <== Difference between number of sec when do_something ends and when it started

Lets try it with a simple sleep as "do_something":
$ start=$(date +%s); sleep 2; end=$(date +%s); echo "Time spent: $(( end-start )) seconds"
Time spent: 2 seconds
$

This looks obvious and straightforward and I honestly never thought there would be an easier way (and this is why I never looked for it !). And that better way is a magic bash variables named SECONDS. SECONDS counts the number of seconds since your shell is invocated and you can reset it to 0 when you wish and then make it count whatever you want for you (!) -- meaning that the above code would now be:
SECONDS=0                                                  <== Reset SECONDS to 0
do_something                                               <== Something is running
echo "Time spent: $SECONDS"                                <== Show the time spent by do_something

Which does exactly what we want it to do in a very simple way:
$ SECONDS=0; sleep 2; echo "Time spent: $SECONDS"
Time spent: 2 seconds
$

Note that this does not work if you expect milliseconds; you'll then have to use the first method using date +%s%3Nto get milliseconds:
$ start=$(date +%s%3N); echo "" > /dev/null ; end=$(date +%s%3N); echo "Time spent: $(( end-start )) milliseconds"
Time spent: 3 milliseconds
$

One less opportunity to reinvent the wheel!
< Previous shell tip / Next shell tip coming soon >

1 comment:

Some bash tips -- 17 -- SECONDS

Reinventing the wheel is rooted deep inside our DNA. I really try to never reinvent the wheel but I recently got caught (!). Indeed, wh...