I want to execute something in a linux shell under a few different conditions, and be able to output the execution time of each execution.
I know I could write a perl or python script that would do this, but is there a way I can do it in the shell? (which happens to be bash)
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'stime
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'stime
utility, as demonstrated below (the question is tagged linux); the BSD/macOS implementation uses-l
to produce similar output - seeman 1 time
.Example of verbose output:
If you only need precision to the second, you can use the builtin
$SECONDS
variable, which counts the number of seconds that the shell has been running.Should you want more precision, use
%N
withdate
(and usebc
for the diff, because$(())
only handles integers).Here's how to do it:
Example:
Result:
If you intend to use the times later to compute with, learn how to use the
-f
option of/usr/bin/time
to output code that saves times. Here's some code I used recently to get and sort the execution times of a whole classful of students' programs:I later concatenated all the
$timefile
files and pipe the output into a Lua interpreter. You can do the same with Python or bash or whatever your favorite syntax is. I love this technique.one possibly simple method ( that may not meet different users needs ) is the use of shell PROMPT.it is a simple solution that can be useful in some cases. You can use the bash prompting feature as in the example below:
The above command will result in changing the shell prompt to :
Each time you run a command (or hit enter) returning back to the shell prompt, the prompt will display current time.
notes:
1) beware that if you waited for sometime before you type your next command, then this time need to be considered, i.e the time displayed in the shell prompt is the timestamp when the shell prompt was displayed, not when you enter command. some users choose to hit Enter key to get a new prompt with a new timestamp before they are ready for the next command.
2) There are other available options and modifiers that can be used to change the bash prompt, refer to ( man bash ) for more details.