Finding bottlenecks in bash scripts can be done by defining this function:

# measure execution time of a bash script
# usage: call it two times: (1) to start the clock. (2) then to stop it
time::clock() {
    [ -z "$ts" ] && { ts=`date +%s%N`;return;} || te=`date +%s%N`
    printf "%6.4f" $(echo $((te-ts))/1000000000 | bc -l)
    unset ts te
}

Unlike Unix’s time(1) which measures start-to-end time, time::clock measures execution time of pieces of code:

$ cat script.sh
# ... code ...
time::clock
sleep 0.5
echo "Total time: ${time::clock}"
# ... more code ...

$ ./script.sh
Total time: 0.5060