Time your shell script operations

Pub.

This is a note to self (so I don’t forgot about it) – it is not rocket science 😉

If you need to check how long it takes to run part of your bash script you can use the use PS4 trick, as explained partially here, but it is a bit messy and I don’t like to do the math by hand 😛

In order to test the performance bottleneck of one of my shell scripts I draft a small set of functions.
One to start the clock ticking, another to check how long it passed since the last mark and another to reset the clock.

You can download/copy into a file of your choice and then source it inside your script. The output is the nanoseconds passed between operations. If you make (any) use of it please let me know. I don’t think it will blow up your computer, but you’re at your own risk 😉

#######################################
# Bruno Lucas – v1.0 – 2012/10/22 #
#######################################
TIME_TICKER=0

echoerr() { echo -e “$@” 1>&2; }

function time_start()
{

TIME_TICKER=`date “+%s%N”`

}

#You can pass a message delimited by single quoted
function time_mark()
{

CURR=`date +%s%N`
DIFF=`echo “$CURR – $TIME_TICKER” | bc`
echoerr “$DIFF\t$1”
TIME_TICKER=$CURR

}

function time_reset()
{

TIME_TICKER=0

}

To use:

source timer.sh

time_start

some_op_of_mine 1 2 3 4

time_mark ‘After x’

and you’ll get something like ‘13789137   After x’ telling the elapsed time.

PS: The echoerr function was stolen from here, it echos the content to STDERR, instead of STDOUT.

PS1: Copy/paste from HTML can sometimes come with errors, always check the source code prior to execution.

 

facebooktwittergoogle_plusredditpinterestlinkedinmail

Pub.

Leave a Reply

Pub.