The following methods demonstrate different methods on how to compute the time a potion of code or script take to complete their execution.
Time Methods - Full Examples (141 downloads)
Method 1 – Using date
The following example will calculate the execution time in seconds by subtracting the system date and time in seconds since 1970-01-01 00:00:00 UTC
once right before the script goes to the computation part and once right after.
In order to get the system date and time in seconds since 1970-01-01 00:00:00 UTC
we use the command date +%s
.
Time Methods - Full Examples (141 downloads)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
Method 2 – Using bash internal SECONDS variable
The following example will calculate the execution time in seconds by reseting the bash internal variable SECONDS
to 0, forcing the shell to continue counting from there.
Time Methods - Full Examples (141 downloads)
参考:https://www.oreilly.com/library/view/shell-scripting-expert/9781118166321/c03-anchor-3.xhtml
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Method 3 – Using bash time
The following example uses the bash time command, which reports the time consumed by a pipeline’s execution.
When time command is executed without its complete path, then the bash built-in time command is executed, instead of the GNU time command. We will use the bash time command in this example and we will use it to run a whole block of commands.
Please note that time command will return the time in seconds as a float (i.e. there will be decimal places. e.g. 1 will be printed as 1.00).
Time Methods - Full Examples (141 downloads)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
Method 4 – Using GNU time
The GNU time command runs the specified program command with the given arguments.
When time command is executed without its complete path (in our case it was /usr/bin/time), then the bash built-in time command is executed, instead of the GNU time command. To make sure we use the GNU time command, we use which to get the full path of the time command.
Please note that time command will return the time in seconds as a float (i.e. there will be decimal places. e.g. 1 will be printed as 1.00).
Time Methods - Full Examples (141 downloads)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
Notes
RANDOM internal variable
Each time RANDOM
internal variable is referenced, a random integer between 0
and 32767
is generated.
By using the RANDOM
variable in this command $(( (RANDOM % 10) + 1 ));
we perform a modulo on the random value with the static value 10. This way we force the range of valid values to be between 0
and 9
.
Later, we add 1 to that value to shift the range to be between 1
and 10
.
原文:https://bytefreaks.net/gnulinux/bash/get-execution-time-in-seconds