Main index

Introducing UNIX and Linux


Processes and devices

Overview
Processes
      Process status
      Foreground and background
      Process control
      Signals
Environment
      Environment variables
      Global and local variables
      Executable scripts
Program control
      Job control
      Command history list
      Running a job at a specific time
      Running programs periodically
      Big programs
      Timing a program
      Running programs in order
Quotes and escapes
Devices
Backquotes
Summary
Exercises

Timing a program

It's often useful to know how long it takes to run a command. Perhaps you need to compare the speeds of different machines (if you have access to more than one) in order to choose the fastest machine. Perhaps you need to know if a program takes a long time to run so that you can schedule it when you run it again at a quiet time of day. The command time provides this information. With no options, time followed by a simple command (that is, not a pipeline or other complex shell construct) displays some statistics on the standard error stream. Note that the statistics generated by time, and the format, vary on different systems.

A more concise output can be obtained by running time with option -p. In this case, only three numbers will be given. First, the total real (or elapsed) time (in seconds) the command took to run is displayed and then the processing time spent by the user's command executing on the processor. Finally, the time spent by the system (for example, moving processes in and out of the processor) is displayed:

time date
Fri Dec  7 09:45:32 GMT 2001
real    0m0.063s
user    0m0.010s
sys     0m0.042s

time -p
Fri Dec  7 09:47:02 GMT 2001
real 0.6
user 0.1
sys 0.4

If the system is busy, the real time will be larger, since there will be many users running processes, all of which demand their fair share of processor time. However, for a particular command (such as date) the user and the system times ought to remain fairly constant, since that command will do the same work each time it is run. Try timing the sleep command:

time sleep 5
real 5.7
user 0.3
sys 0.3

You will see that the total time for the command to run was slightly over 5 seconds, but the amount of processing time - and thus the work the system had to do - was very small in comparison. This is to be expected, since sleep does nothing anyway. The times for the system and user are the actual processing time, and exclude any idle time when the relevant processes are not running, so that the real time will always be at least the sum of the user and system time. If you wish to time a complex command, which is not a single word with arguments, then a simple way to do it is to create a shell script containing the command and time the execution of that script.


Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck