Use the date Command to Measure Elapsed Time
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.
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Designing Electronics with Linux | May 22, 2013 |
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
- New Products
- Linux Systems Administrator
- Senior Perl Developer
- Technical Support Rep
- UX Designer
- Web & UI Developer (JavaScript & j Query)
- Designing Electronics with Linux
- Dynamic DNS—an Object Lesson in Problem Solving
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Using Salt Stack and Vagrant for Drupal Development
- Reply to comment | Linux Journal
2 hours 27 min ago - Nice article, thanks for the
13 hours 8 min ago - I once had a better way I
18 hours 53 min ago - Not only you I too assumed
19 hours 11 min ago - another very interesting
21 hours 4 min ago - Reply to comment | Linux Journal
22 hours 57 min ago - Reply to comment | Linux Journal
1 day 5 hours ago - Reply to comment | Linux Journal
1 day 6 hours ago - Favorite (and easily brute-forced) pw's
1 day 7 hours ago - Have you tried Boxen? It's a
1 day 13 hours ago
Enter to Win an Adafruit Pi Cobbler Breakout Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Pi Cobbler Breakout Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
Featured Jobs
| Linux Systems Administrator | Houston and Austin, Texas | Host Gator |
| Senior Perl Developer | Austin, Texas | Host Gator |
| Technical Support Rep | Houston and Austin, Texas | Host Gator |
| UX Designer | Austin, Texas | Host Gator |
| Web & UI Developer (JavaScript & j Query) | Austin, Texas | Host Gator |
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?



Comments
another way
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
It looks so simple when you put it that way :{) !
Indents are purty
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?
I don't see a problem with using "time". It doesn't work quite as expected, but it can be made to work:
And if you want time's output to go to a log, redirect stderr:
You could redirect the stderr of commands inside the block of code somewhere else, e.g. to another logfile.
Works Best for LISP Programmers
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
Indents. How we laughed.
Unnecessary in bash.
So, you agree then?