Get program execution time in the shell
Use the built-in time
keyword:
$ help time 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:
$ time sleep 2
real 0m2.009s user 0m0.000s sys 0m0.004s
You can get much more detailed information than the bash built-in time
(which Robert Gamble mentions) using time(1). Normally this is /usr/bin/time
.
Editor's note:
To ensure that you're invoking the external utility time
rather than your shell's time
keyword, invoke it as /usr/bin/time
.
time
is a POSIX-mandated utility, but the only option it is required to support is -p
.
Specific platforms implement specific, nonstandard extensions: -v
works with GNU's time
utility, as demonstrated below (the question is tagged linux); the BSD/macOS implementation uses -l
to produce similar output - see man 1 time
.
Example of verbose output:
$ /usr/bin/time -v sleep 1
Command being timed: "sleep 1"
User time (seconds): 0.00
System time (seconds): 0.00
Percent of CPU this job got: 1%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:01.05
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 0
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 0
Minor (reclaiming a frame) page faults: 210
Voluntary context switches: 2
Involuntary context switches: 1
Swaps: 0
File system inputs: 0
File system outputs: 0
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0
#!/bin/bash
START=$(date +%s)
# do something
# start your script work here
ls -R /etc > /tmp/x
rm -f /tmp/x
# your logic ends here
END=$(date +%s)
DIFF=$(( $END - $START ))
echo "It took $DIFF seconds"