Use the date Command to Measure Elapsed Time

 in

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.

Comments

Comment viewing options

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

another way

Anonymous's picture

I've just used the time program (which is present in all the linux distros I've seen so far). The usage is quite simple, ie:

----------------------
#!/bin/bash

time (
something
)
----------------------

It'll print out a nice (and configurable) info about the elapsed time doing the something stuff.

----------------------
real 0m13.109s
user 0m7.772s
sys 0m0.772s

----------------------

It looks so simple when you

Bug's picture

It looks so simple when you put it that way :{) !

Indents are purty

Blurry's picture

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

Maybe im doing it wrong.

& Thanks Mitch, thats handy!

Why go to all that trouble?

RichS's picture

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.

Works Best for LISP Programmers

Mitch Frazier's picture

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.

Cute

RichS's picture

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

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix