Get program execution time in the shell
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)
11 Answers 11
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.
real 0m2.009s user 0m0.000s sys 0m0.004s
How is this used on a command like time -p i=x; while read line; do x=x; done < /path/to/file.txt ? It immediatly returns 0.00 unless I don't put anything before the while loop.. what gives?
@natli: While time can time an entire pipeline as-is (by virtue of being a Bash keyword), you need to use a group command ( < . ; . ; >) to time multiple commands: time -p < i=x; while read line; do x=x; done < /path/to/file.txt; >
You can get much more detailed information than the bash built-in time (i.e time(1), which Robert Gamble mentions). 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
Bash время выполнение скрипта в милисекундах
Есть обычный тестовый скрипт, который копирует содержимое папки и показывает в конце время выполнения операции. Но это время указывается в секундах, а реальный скрипт может выполняться гораздо быстрее и обычно мне возвращается 0 секунд, хотя он то может быть выполнен за 0,5 сек или 0,005 сек. Вопрос: Есть ли возможность подсчёта времени в милисекундах?
#!/bin/bash START=$(date +%s) # начало скрипта cp -r /home/it/Downloads /home/it/Downloads/bash-time # конец скрипта END=$(date +%s) DIFF=$(( $END - $START )) echo "It took $DIFF seconds"
bash имеют встроенную команду time в случае если нужен настраиваемый вывод, то следует обращаться напрямую /usr/bin/time, к примеру команда /usr/bin/time -f %E sleep 0.03 вернет фактически затраченное время на выполнение команды sleep 0.03 .
3 ответа 3
Используя ваш код немного модифицируем и получим следующее:
#!/bin/bash START=$(date +%s%N) # начало скрипта cp -r /home/it/Downloads /home/it/Downloads/bash-time # конец скрипта END=$(date +%s%N) DIFF=$(($($END - $START)/1000000)) echo "It took $DIFF milliseconds"
Аргумент %N вернет наносекунды, 1 миллисекунда равна 1000000 наносекундам.
UPD: Не проверял, но должно работать.
DIFF=$(($($END — $START)/1000000)) лишний знак доллара у вас в команде: DIFF=$((($END — $START)/1000000))
real 0m0,125s user 0m0,001s sys 0m0,001s
Для вывода минут секунд и тысячных секунды можно использовать следующую конструкцию скрипта:
#!/bin/bash TIMEFORMAT="время выполнения %lR" time < cp -r /home/it/Downloads /home/it/Downloads/bash-time #Набор команд, возможно использование функций #и конструкций проверки типа [ $a ] && < echo 1; exit 0; >> #конец скрипта либо exit
Вывод:
время выполнения 1m2.004s
Таймер возвращает общее время выполнения перечисленных команд между родительскими < >, возможно так же вызвать несколько time <. >в одном скрипте и переобъявить переменную TIMEFORMAT для каждого.
Более подробно о формате вывода времени команды time можно почитать тут http://www.gnu.org/software/bash/manual/html_node/Bash-Variables.html
UPD: если вы изменили переменную TIMEFORMAT в терминале и хотите вернуть ее в текущей сессии по умолчанию, то выполните команду unset TIMEFORMAT .
How to get script execution time from within the shell script in Linux
In my last article I shared examples to get script name and script path in a shell script, Now let me help you with some examples to find out the elapsed time in minutes using bash script. Bash script execution time. Get script execution time in shell script. How to get command execution time in Unix. bash script start end time. How to calculate script execution time in Unix. bash get command execution time.
There are two parts of this question.
- Get script execution time or command execution time externally
- Get script execution time internally
Get script execution time externally
You can use ‘ time ‘ command to get the execution time of the script. This command will call the Tcl interpreter count times to evaluate script (or once if count is not specified). It will then return a string of the form 503 microseconds per iteration which indicates the average amount of time required per iteration, in microseconds.
# time /tmp/script.sh Script Execution Time: 5.00 seconds real 0m5.015s user 0m0.005s sys 0m0.014s
Here,
real or total or elapsed (wall clock time) is the time from start to finish of the call. It is the time from the moment you hit the Enter key until the moment the script execution completed.
user — amount of CPU time spent in user mode.
system or sys — amount of CPU time spent in kernel mode.
Get command execution time
Use the time command in the below format to get command execution time. At the end of execution the time command will give you the execution time values. You can further user awl/grep/sed to get the required details.
# time rpm -Uvh /export/home/iserver/linux/install/Linux/rhel7_64/Packages/atk-2.22.0-3.el7.x86_64.rpm Preparing. ################################# [100%] Updating / installing. 1:atk-2.22.0-3.el7 ################################# [100%] real 0m0.104s user 0m0.077s sys 0m0.027s
The output is same as explained above.
Get script execution time internally
Here it gets tricky as the time command can be only called externally but if you wish to get a script execution time from within the script then we have to put some function within the script.
Below I have created a dummy script to measure the script execution time internally
#!/bin/bash # This should be at the top of the script to get the start time of the script start=$(date +%s.%N) # Here you can place your function sleep 5 duration=$(echo "$(date +%s.%N) - $start" | bc) execution_time=`printf "%.2f seconds" $duration` echo "Script Execution Time: $execution_time"
Let us execute our script
# /tmp/script.sh Script Execution Time: 5.00 seconds
So our script ran for 5 seconds.
But this is not a very reliable solution because if the script exits abruptly then the script will fail to print the execution time. So we have to take some extra measures to make sure in any case the script makes sure it gets the script duration.
But that would vary from script to script so I can not predict that here.
You can write some function for exit such as
# This should be at the top of the script to get the start time of the script start=$(date +%s.%N) function exit_with_error
So now you can use exit_with_error function for all possible scenarios where your script could exit, so that you get script execution time properly for all success and failure scenarios.
Lastly I hope the steps from the article to check or get command execution time and to get the script execution time from within the shell script in Linux was helpful. So, let me know your suggestions and feedback using the comment section.
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!