Shell scripting: logging elapsed time

This is as much a note for myself as it is for anyone else, but I’m executing a couple shell scripts via cron that I’d very much like to be able to time. I know they take from less than a second to a couple of seconds to complete, and would like to be able to log the elapsed time.

The common way Google presents is as follows:

There is one glaring problem with this – for me anyway. bash and sh don’t work with fractions of a second (or floating point/decimal numbers at all) so the difference will always be a whole number.

Seeing “2 seconds” is fine, but I’m interested in it being “2.255322 seconds.” A better solution:

First, we change the date format to

date +%s%N

Adding the %N gets us nanoseconds instead of seconds – as whole numbers, that is. (Note: %N doesn’t work on BSD variants.) So we divide by 1 billion, and pipe the calculation string through bc, a unix calculator, and it will return our seconds difference to 8 decimal places.

This changes my output from:

Backup complete in 2 seconds

to:

Backup complete in 2.83732828 seconds

Much better :)

  • oraclebill

    Hmm.. why not just use the ‘time’ command?

  • http://davemartorana.com Dave Martorana

    I use the $ELAPSED variable afterwards to send to a process monitor (Dead Man’s Snitch –¬†https://nosnch.in/ ) using curl later on in the same shell script. This is good for timing a subsection of a shell script.