456

I would like to display the completion time of a script.

What I currently do is -

#!/bin/bash
date  ## echo the date at start
# the script contents
date  ## echo the date at end

This just show's the time of start and end of the script. Would it be possible to display a fine grained output like processor time/ io time , etc?

17 Answers 17

588

Just use time when you call the script:

time yourscript.sh
| improve this answer | |
  • 83
    This outputs three times: real, user and sys. For the meanings of these, see here. – Garrett Jul 9 '15 at 1:56
  • 45
    and "real" is probably what people want to know - "Real is wall clock time - time from start to finish of the call" – Brad Parks Mar 29 '16 at 12:19
  • 6
    Is there a way to capture the stdout into a file? For example, something like time $( ... ) >> out.txt – Jon Apr 25 '18 at 18:18
  • 2
    You can also do this to sequences of commands on the command line, eg: time (command1 && command2) – meetar Apr 25 '18 at 20:30
  • 3
    Or he could, in his script, just do: echo $SECONDS assuming it is bash.... – Scott Prive Feb 22 '19 at 17:10
229

If time isn't an option,

start=`date +%s`
stuff
end=`date +%s`

runtime=$((end-start))
| improve this answer | |
  • 34
    Note that this only works if you don't need sub-second precision. For some uses that might be acceptable, for others not. For slightly better precision (you're still invoking date twice, for example, so you might at best get millisecond precision in practice, and probably less), try using date +%s.%N. (%N is nanoseconds since the whole second.) – user Oct 19 '12 at 19:17
  • 4
    @ChrisH Oh. Good pointing it out; bash arithmetic expansion is integer-only. I see two obvious options; either ditch the period in the date format string (and treat the resultant value as nanoseconds since epoch), so use date +%s%N, or use something more capable like bc to calculate the actual runtime from the two values like jwchew suggests. Still, I feel this approach is a suboptimal way of doing it; time is considerably better if available, for reasons outlined above. – user Jan 23 '14 at 13:29
  • 12
    Just install bc and then do this: runtime=$( echo "$end - $start" | bc -l ) – redolent Feb 11 '15 at 22:01
  • 12
    If your script takes several Minutes, use: echo "Duration: $((($(date +%s)-$start)/60)) minutes – rubo77 Jul 29 '16 at 4:42
  • 2
    Further to @rubo77 comment, if your script takes several hours use hours=$((runtime / 3600)); minutes=$(( (runtime % 3600) / 60 )); seconds=$(( (runtime % 3600) % 60 )); echo "Runtime: $hours:$minutes:$seconds (hh:mm:ss)" – Tom Nov 13 '19 at 15:24
82

Just call times without arguments upon exiting your script.

With ksh or zsh, you can also use time instead. With zsh, time will also give you the wall clock time in addition to the user and system CPU time.

To preserve the exit status of your script, you can make it:

ret=$?; times; exit "$ret"

Or you can also add a trap on EXIT:

trap times EXIT

That way, times will be called whenever the shell exits and the exit status will be preserved.

$ bash -c 'trap times EXIT; : {1..1000000}'
0m0.932s 0m0.028s
0m0.000s 0m0.000s
$ zsh -c 'trap time EXIT; : {1..1000000}'
shell  0.67s user 0.01s system 100% cpu 0.677 total
children  0.00s user 0.00s system 0% cpu 0.677 total

Also note that all of bash, ksh and zsh have a $SECONDS special variable that automatically gets incremented every second. In both zsh and ksh93, that variable can also be made floating point (with typeset -F SECONDS) to get more precision. This is only wall clock time, not CPU time.

| improve this answer | |
  • 13
    That $SECONDS variable is very useful, thanks! – andybuckley Jun 18 '14 at 12:00
  • 1
    Does your approach eliminate the effect of temporal events? - - I think your approach is near time approach presented earlier. - - I think the timeit approach presented in MATLAB code can be useful here. – Léo Léopold Hertz 준영 Dec 25 '16 at 9:37
  • 2
    Hi, @Stéphane Chazelas. I found times doesn't give wall time, right? for example, bash -c 'trap times EXIT;sleep 2' – user15964 Jun 13 '17 at 2:17
  • Similar to unix.stackexchange.com/questions/269789/… – akhan Sep 10 '18 at 2:24
37

I'm a bit late to the bandwagon, but wanted to post my solution (for sub-second precision) in case others happen to stumble upon this thread through searching. The output is in format of days, hours, minutes, and finally seconds:

res1=$(date +%s.%N)

# do stuff in here

res2=$(date +%s.%N)
dt=$(echo "$res2 - $res1" | bc)
dd=$(echo "$dt/86400" | bc)
dt2=$(echo "$dt-86400*$dd" | bc)
dh=$(echo "$dt2/3600" | bc)
dt3=$(echo "$dt2-3600*$dh" | bc)
dm=$(echo "$dt3/60" | bc)
ds=$(echo "$dt3-60*$dm" | bc)

LC_NUMERIC=C printf "Total runtime: %d:%02d:%02d:%02.4f\n" $dd $dh $dm $ds

Hope someone out there finds this useful!

| improve this answer | |
  • 1
    I guess there is no other (only bash) way except using 'bc' to do the calculations. BTW really good script ;) – tvl Apr 18 '16 at 1:19
  • 1
    Beware that FreeBSD's date does not support sub-second precision and will just append literal “N” to the timestamp. – Anton Samsonov Jul 12 '16 at 9:25
  • 1
    Very nice script, but my bash doesn't handle the subsecond part. I also learned, that /1 in bc effectively strips that, so I added @/1@ to the $ds calculation, and it displays stuff very nice now! – Daniel Feb 1 '17 at 6:00
  • 1
    bc supports modulo: dt2=$(echo "$dt%86400" | bc). Just saying... BTW I prefer the form dt2=$(bc <<< "${dt}%86400") but that's entirely personal. – Dani_l Mar 7 '18 at 16:06
30

My method for bash:

# Reset BASH time counter
SECONDS=0
    # 
    # do stuff
    # 
ELAPSED="Elapsed: $(($SECONDS / 3600))hrs $((($SECONDS / 60) % 60))min $(($SECONDS % 60))sec"
| improve this answer | |
  • 2
    This does show elapsed time, but it doesn't show "fine grained output like processor time, I/O time" as requested in the question. – roaima Jan 25 '17 at 22:10
  • 6
    Those searching for an answer to the question as posed are likely to find this solution useful. Your comment would be better addressed to the OPs question. – Mark Jan 26 '17 at 0:51
15

Personally, I like to wrap all my script code in some "main" function like so:

main () {
 echo running ...
}

# stuff ...

# calling the function at the very end of the script
time main

Notice how easy is to use the time command in this scenario. Obviously you're not measuring the precise time including script parse time, but I find it accurate enough in most situations.

| improve this answer | |
  • 1
    Great solution, doesn't require extra tools and is self contained. – Cameron Wilby May 3 at 22:05
11

This question is quite old but in trying to find my favorite way of doing it this thread came up high... and I'm surprised no one mentioned it:

perf stat -r 10 -B sleep 1

'perf' is a performance analyzing tool included in the kernel under 'tools/perf' and often available to install as a separate package ('perf' in CentOS and 'linux-tools' on Debian/Ubuntu). The Linux Kernal perf Wiki has much more information about it.

Running 'perf stat' gives quite a bit of details including average execution time right at the end:

1.002248382 seconds time elapsed                   ( +-  0.01% )
| improve this answer | |
  • 3
    What is perf? – B Layer Feb 20 '18 at 14:10
  • @B Layer - edited my answer to give a brief description of 'perf'. – zbateson Feb 21 '18 at 15:42
  • 1
    perf stat now complains about "You may not have permission to collect stats." unless you run some commands with sudo, which makes it useless in all scenarios where you don't completely own target machine. – alamar Nov 22 '18 at 13:30
  • Amazing, thanks! Way more fine-grained solution than time others suggesting. In particular, time is not applicable to measuring code competition solutions (as it doesn't print time in milliseconds and less), whereas your solution does. – Hi-Angel Mar 8 at 14:25
10
#!/bin/bash
start=$(date +%s.%N)

# HERE BE CODE

end=$(date +%s.%N)    
runtime=$(python -c "print(${end} - ${start})")

echo "Runtime was $runtime"

Yes, this calls Python, but if you can live with that then this is quite a nice, terse solution.

| improve this answer | |
  • 6
    Beware that running that python command in a subshell and reading its output will take several millions of nanoseconds on most current systems. Same for running date. – Stéphane Chazelas Nov 22 '14 at 10:58
  • 10
    "Several millions of nanoseconds" is several milliseconds. People timing bash scripts are usually not very concerned about that (unless they run several billions of scripts per megasecond). – Zilk Jan 1 '16 at 3:34
  • 4
    Notice also that, even if the calculation is done inside a python process, the values were entirely collected before python was invoked. The execution time of the script will be measured correctly, without the "millions of nanoseconds" overhead. – Victor Schröder Feb 19 '19 at 10:07
  • time main above is so much more clean... yes, we can live with lots of degradation but it's way better without so let's stay engineers! – Michael Shigorin Jul 30 at 18:11
  • $(echo $end - $start | bc) will do the same thing without python – James McGuigan Nov 16 at 1:09
6

A small shell function that can be added before commands to measure their time:

tm() {
  local start=$(date +%s)
  $@
  local exit_code=$?
  echo >&2 "took ~$(($(date +%s)-${start})) seconds. exited with ${exit_code}"
  return $exit_code
}

Then use it in your script, or on your command line like so:

tm the_original_command with all its parameters
| improve this answer | |
5
#!/bin/csh
#PBS -q glean
#PBS -l nodes=1:ppn=1
#PBS -l walltime=10:00:00
#PBS -o a.log
#PBS -e a.err
#PBS -V
#PBS -M shihcheng.guo@gmail.com
#PBS -m abe
#PBS -A k4zhang-group
START=$(date +%s)
for i in {1..1000000}
do
echo 1
done
END=$(date +%s)
DIFF=$(echo "$END - $START" | bc)
echo "It takes DIFF=$DIFF seconds to complete this task..."
| improve this answer | |
  • 7
    How is this really different from the other answers already given which use date before and after the script and output the difference between them? – Eric Renouf Jan 15 '16 at 4:11
5
  1. Just use time [any command]. Ex: time sleep 1 will sleep for a real time (ie: as timed by a stop watch) of ~1.000 to ~1.020 sec, as shown here:

     $ time sleep 1
    
     real    0m1.011s
     user    0m0.004s
     sys 0m0.000s
    

    What a beautiful thing. You can put any command after it, and it outputs the result in a nice, human-readable form. I really like to use it for timing builds. Ex:

     # time your "make" build
     time make
    
     # time your "Bazel" build
     time bazel build //path/to/some:target
    

    ...or for git operations which can potentially be really long, so I can develop realistic mental expectations:

     # time how long it takes to pull from a massive repo when
     # I'm working from home during COVID-19. NB: `git pull`
     # is sooooo much slower than just pulling the one branch
     # you need with `git pull origin <branch>`, so just fetch
     # or pull what you need!
     time git pull origin master
    
  2. For more-customized timing needs where you may need to manipulate the output or convert it to other forms, in bash, use the internal $SECONDS variable. Here's a demo, including converting these seconds to other units, such as floating point minutes:

    Note that dt_min gets rounded from 0.01666666666... (1 second = that many minutes) to 0.017 in this case since I'm using the printf function to round. The sleep 1; part below is where you'd call your script to run and time, but I'm just sleeping for 1 second instead for the sake of this demo.

    Command:

     start=$SECONDS; sleep 1; end=$SECONDS; dt_sec=$(( end - start )); \
     dt_min=$(printf %.3f $(echo "$dt_sec/60" | bc -l)); \
     echo "dt_sec = $dt_sec; dt_min = $dt_min"
    

    Output:

     dt_sec = 1; dt_min = 0.017
    

Related:

  1. Read more about bc and printf in my answer here: https://stackoverflow.com/questions/12722095/how-do-i-use-floating-point-division-in-bash/58479867#58479867
  2. I don't remember where I first learned about the time command anymore, but it may have been from @Trudbert's answer right here.
| improve this answer | |
3

Using only bash it is also possible to measure and calculate the time duration for a portion of the shell script (or the elapsed time for the entire script):

start=$SECONDS

... # do time consuming stuff

end=$SECONDS

you can now either just print the difference:

echo "duration: $((end-start)) seconds."

if you only need incremental duration do:

echo "duration: $((SECONDS-start)) seconds elapsed.."

You can also store the duration in a variable:

let diff=end-start
| improve this answer | |
  • 1
    ^ THIS is the answer folks. Or more simply: $SECONDS at the end. It's a BUILT-IN Bash variable. All of the other answers are just doing extra work to re-invent this wheel... – Scott Prive Feb 22 '19 at 17:08
  • This is just a repetition of Marks earlier answer unix.stackexchange.com/a/340156/155362. – Juergen Aug 18 at 1:29
3

Timing function based on SECONDS, limited to second-level granularity only, doesn't use any external commands:

time_it() {
  local start=$SECONDS ts ec
  printf -v ts '%(%Y-%m-%d_%H:%M:%S)T' -1
  printf '%s\n' "$ts Starting $*"
  "$@"; ec=$?
  printf -v ts '%(%Y-%m-%d_%H:%M:%S)T' -1
  printf '%s\n' "$ts Finished $*; elapsed = $((SECONDS-start)) seconds"
  # make sure to return the exit code of the command so that the caller can use it
  return "$ec"
}

For example:

time_it sleep 5

gives

2019-03-30_17:24:37 Starting sleep 5 2019-03-30_17:24:42 Finished
sleep 5; elapsed = 5 seconds
| improve this answer | |
2

Here's a variation of Alex's answer. I only care about minutes and seconds, but I also wanted it formatted differently. So I did this:

start=$(date +%s)
end=$(date +%s)
runtime=$(python -c "print '%u:%02u' % ((${end} - ${start})/60, (${end} - ${start})%60)")
| improve this answer | |
  • 1
    Why the downvote? Do I have a bug? – mpontillo Dec 25 '16 at 20:43
  • Using python for that calculation looks like a bug to me either, sorry man. Why people can't just call time is beyond me. – Michael Shigorin Jul 30 at 18:13
2
#!/bin/bash
begin=$(date +"%s")

Script

termin=$(date +"%s")
difftimelps=$(($termin-$begin))
echo "$(($difftimelps / 60)) minutes and $(($difftimelps % 60)) seconds elapsed for Script Execution."
| improve this answer | |
2

Use bash time builtin?

time: time [-p] PIPELINE
    Execute PIPELINE and print a summary of the real time, user CPU time,
    and system CPU time spent executing PIPELINE when it terminates.
    The return status is the return status of PIPELINE.  The `-p' option
    prints the timing summary in a slightly different format.  This uses
    the value of the TIMEFORMAT variable as the output format.

Example:

TIMEFORMAT="The command took %Rs"
time {
    sleep 0.1
}

Output:

The command took 0.108s
| improve this answer | |
2

The accepted solution using time writes to stderr.
The solution using times writes to stdout.
The solutions using $SECONDS are missing sub-second precision.
The other solutions involve calling external programs like date or perf which is not efficient.
If you are fine with any of these, use it.

But if you need an efficient solution to get the times with millisecond precision and need them into variables such that the original output remains undisturbed you may combine process substitution with some redirections around time which is much faster than calling external programs and allows redirections around the timing wrapper script as on the original command/script.

# Preparations:
Cmd=vgs  # example of a program to be timed which is writing to stdout and stderr
Cmd="eval { echo stdout; echo stderr >&2; sleep 0.1; }"  # other example; replace with your own
TIMEFORMAT="%3R %3U %3S"  # make time output easy to parse

Select one of the following variants parsing the output of time appropriate to you needs:
Shortest variant where stdout of $Cmd is written to stderr and nothing to stdout:

read Elapsed User System < <({ time $Cmd 2>&3; } 3>&2 2>&1 >&3)

Longer variant that keeps original stdout and stderr separate of each other:

{ read Elapsed User System < <({ time $Cmd 2>&4; } 4>&2 2>&1 >&3); } 3>&1

Most complicated variant includes closing the extra file descriptors such that $Cmd is called as if without this timing wrapper around it and lvm commands like vgs do not complain about leaked file descriptors:

{ read Elapsed User System < <({ time $Cmd 2>&4 4>&-; } 4>&2 2>&1 >&3 3>&-); } 3>&1

You can even fake a floating point addition in bash without calling bc which would be much slower:

CPU=`printf %04d $((10#${User/.}+10#${System/.}))`  # replace with your own postprocessing
echo CPU ${CPU::-3}.${CPU: -3} s, Elapsed $Elapsed s >&2  # redirected independent of $Cmd

Possible outputs with the two examples of $Cmd on a slow CPU:

File descriptor 3 (/dev/pts/1) leaked on vgs invocation. Parent PID 10756: bash
File descriptor 4 (/dev/pts/1) leaked on vgs invocation. Parent PID 10756: bash
  VG   #PV #LV #SN Attr   VSize VFree
  b3     3  24   0 wz--n- 1.31t 1.19t
CPU 0.052 s, Elapsed 0.056 s

Or:

stdout
stderr
CPU 0.008 s, Elapsed 0.109 s
| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.