Use the date Command to Measure Elapsed Time

November 26th, 2008 by Mitch Frazier in

Your rating: None Average: 3.8 (6 votes)

When running bash scripts that take a long time to run it's often useful to know how long it took for the script to run. In addition to the overall run time, it's also often useful to know how long certain parts of the script took to run. The time command doesn't really help because it's meant to time a single command, not a sequence of commands. By using the %s format of date the script described here allows you to create as many timers as you want and time whatever part of a script you want.

The %s format of the date command outputs the number of seconds since Unix time began:

  $ date +'%s'
  1227068222

Using two of these values you can determine the elapsed time.

The following script defines a single bash function: timer. If called with no arguments it outputs the current second count. If called with an argument it assumes the argument is a value previously obtained by calling timer with no arguments and it outputs the time that has elapsed since the first value was obtained.

#!/bin/bash
#
# Elapsed time.  Usage:
#
#   t=$(timer)
#   ... # do something
#   printf 'Elapsed time: %s\n' $(timer $t)
#      ===> Elapsed time: 0:01:12
#
#
#####################################################################
# If called with no arguments a new timer is returned.
# If called with arguments the first is used as a timer
# value and the elapsed time is returned in the form HH:MM:SS.
#
function timer()
{
    if [[ $# -eq 0 ]]; then
        echo $(date '+%s')
    else
        local  stime=$1
        etime=$(date '+%s')

        if [[ -z "$stime" ]]; then stime=$etime; fi

        dt=$((etime - stime))
        ds=$((dt % 60))
        dm=$(((dt / 60) % 60))
        dh=$((dt / 3600))
        printf '%d:%02d:%02d' $dh $dm $ds
    fi
}

# If invoked directly run test code.
if [[ $(basename $0 .sh) == 'timer' ]]; then
    t=$(timer)
    read -p 'Enter when ready...' p
    printf 'Elapsed time: %s\n' $(timer $t)
fi

## vim: tabstop=4: shiftwidth=4: noexpandtab:
## kate: tab-width 4; indent-width 4; replace-tabs false;

To use the function first obtain a starting timer value in the following manner:

  tmr=$(timer)

Then when you want to know how much time has elapsed, pass the original timer value and print the result. For example, to print the timer obtained above:

  printf 'Elapsed time: %s\n' $(timer $tmr) 

Running the timer.sh script directly runs it in test mode. It obtains a timer, waits for you to hit enter, then prints the elapsed time:

  $ sh timer.sh
  Enter when ready...
  # Wait a while here
  Elapsed time: 0:01:12
__________________________

Mitch Frazier is an Associate Editor for Linux Journal and the Web Editor for linuxjournal.com.


Special Magazine Offer -- Free Gift with Subscription
Receive a free digital copy of Linux Journal's System Administration Special Edition as well as instant online access to current and past issues. CLICK HERE for offer

Linux Journal: delivering readers the advice and inspiration they need to get the most out of their Linux systems since 1994.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Blurry's picture

Indents are purty

On December 4th, 2008 Blurry (not verified) says:

I always indent, its easier to read & spot bad syntax?

Maybe im doing it wrong.

& Thanks Mitch, thats handy!

RichS's picture

Why go to all that trouble?

On November 26th, 2008 RichS (not verified) says:

I don't see a problem with using "time". It doesn't work quite as expected, but it can be made to work:

  time echo $( 
  # code to be timed goes here
  )

And if you want time's output to go to a log, redirect stderr:

  ( time echo $( 
  # code to be timed goes here
  ) ) 2>logfile

You could redirect the stderr of commands inside the block of code somewhere else, e.g. to another logfile.

Mitch Frazier's picture

Works Best for LISP Programmers

On November 28th, 2008 Mitch Frazier says:

That'll work, but it gets a bit harry if you want to also time sub-parts of the part you're timing:

  time echo $( 
      # code to be timed goes here
      time echo $( 
          # code to be timed goes here
          time echo $( 
              # code to be timed goes here
              time echo $( 
                  # code to be timed goes here
              )
          )
      )
  )
__________________________

Mitch Frazier is an Associate Editor for Linux Journal and the Web Editor for linuxjournal.com.

RichS's picture

Cute

On December 2nd, 2008 RichS (not verified) says:

Indents. How we laughed.
Unnecessary in bash.
So, you agree then?

Post new comment

Please note that comments may not appear immediately, so there is no need to repost your comment.
The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <pre> <ul> <ol> <li> <dl> <dt> <dd> <i> <b>
  • Lines and paragraphs break automatically.

More information about formatting options

Newsletter

Each week Linux Journal editors will tell you what's hot in the world of Linux. You will receive late breaking news, technical tips and tricks, and links to in-depth stories featured on www.linuxjournal.com.
Sign up for our Email Newsletter

Tech Tip Videos

From the Magazine

August 2009, #184

If you're a culinary type you've probably heard of Pickled Capers. This month, we present you with an even tastier treat: Kerneled Kapers. That's right Linux so good that you can eat it for dinner. We've got two articles about kernel scheduling: one about real time scheduling and the other about the Completely Fair Scheduler which appeared in Linux 2.6.23. We also have an article on the new Ksplice technology that appeared on the scene just recently. Also in this issue: find out how to make root unprivileged.


And if Kapers aren't your cup of tea we have our usual buffet of articles: eyeOS which allows you to create your own cloud based desktops, using fixtures and factories with Rails, more on secure Squids, a review of the long awaited KOffice 2.0, Longomatch, and Kanatest.


But don't leave before we serve up the "piece de resistance": Point/Counterpoint on Twitter.


Apologies to Chef Marcel for borrowing his shtick.





Read this issue