- Bash время выполнение скрипта в милисекундах
- 3 ответа 3
- Check How Long A Bash Script Takes to Run With Time Command
- Using time command
- Time with a text-based application
- Time with a GUI application
- Traditional GNU Version
- GNU Time -p = (bash) time
- Conclusion
- How can I measure the execution time of a terminal process?
- 8 Answers 8
- How do you time how long a command took to run? [duplicate]
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 .
Check How Long A Bash Script Takes to Run With Time Command
The time command in Linux measures how long a particular command or script runs. Learn how to use this command.
This is a simple command that measures… you guessed it, time. It is not a clock application, though. It measures the time taken in running a program or script.
[email protected]:~$ time ./script.sh real 0m12.010s user 0m0.004s sys 0m0.006s
I’ll explain the time command and its output in a minute.
There are a few different versions of the time utility. Here we will be looking at the Bash version, since this is the one you’re most likely to encounter on your system. There is also a Zsh version and a GNU version.
Let’s avoid confusion and verify your version now.
[email protected]:~$ type time time is a shell keyword
If your output looks like this, that’s perfect. That means that you are using bash. The command performs the same task in all its iterations, so if you’re not using bash, fear not, you will still be able to understand what is happening. However, it may look quite different.
Using time command
Time command measures the following:
- real time: total time elapsed
- user: OS processing in user Mode
- sys: OS processing in kernel mode
It can be used with any command or piped commands.
Time with a text-based application
Let’s look at an example with nano. Nano is a terminal based text editor. If I start nano and then promptly exit through the application (Ctrl+X), the output will look like this:
time nano real 0m1.465s user 0m0.031s sys 0m0.006s
Time with a GUI application
This also works with a GUI application. The output will be returned once the application is exited normally or if an interrupt (CTRL+C) is input at the terminal.
time firefox real 0m6.784s user 0m4.962s sys 0m0.459s
Traditional GNU Version
As I touched on before, most Linux users run Bash, which essentially uses a shortcut to create human readable content. You can run the full GNU version by using the escape character \ . This will bypass the built-in shortcut.
This time I will just use sleep command to create a dummy job. The number is the duration in seconds. You will also see this reflected in the output’s real time.
Note that because it is a dummy task, there is no actual resource time devoted to it.
[email protected]:~$ \time sleep 3 0.00user 0.00system 0:03.00elapsed 0%CPU (0avgtext+0avgdata 1944maxresident)k 0inputs+0outputs (0major+75minor)pagefaults 0swaps
This output is a little more difficult to read but it also shares some information about RAM usage that you might find helpful.
GNU Time -p = (bash) time
The output that you normally see with the bash version is kind of like an alias to GNU time run with the -p option.
[email protected]:~$ \time -p sleep 3 real 3.00 user 0.00 sys 0.00
As you can see this gives us the same output as if we had run it with the bash shortcut.
Conclusion
Did you enjoy our guide to the time command? I hope all of these tips taught you something new.
If you like this guide, please share it on social media. If you have any comments or questions, leave them below. If you have any suggestions for topics you’d like to see covered, feel free to leave those as well. Thanks for reading.
How can I measure the execution time of a terminal process?
I’m trying to measure the execution time of a process that I call via the command line (i.e., I want to find out how long it takes to for the process to finish). Is there any command that I can add to the command calling the process that will achieve this?
8 Answers 8
Add time before the command you want to measure. For example: time ls .
The output will look like:
real 0m0.606s user 0m0.000s sys 0m0.002s
Explanation on real , user and sys (from man time ):
- real : Elapsed real (wall clock) time used by the process, in seconds.
- user : Total number of CPU-seconds that the process used directly (in user mode), in seconds.
- sys : Total number of CPU-seconds used by the system on behalf of the process (in kernel mode), in seconds.
@ninjalj, can you provide more information on what the real , user , and sys times are that this command returns?
Note that you may need sudo apt-get install time if you are using a shell where time is not a builtin.
Note that this is the output from Bash’s time builtin, but man time would be about an executable (like /usr/bin/time , from the time package), and its output would look different. Also in Bash, you can run help time for help with the builtin.
Note that the process end does not mean all the work is finished. A copy may take additional minutes after the «time» returns for flushing system bufffers (therefor with unallocated sys time also).
For a line-by-line delta measurement, try gnomon.
It is a command line utility, a bit like moreutils’s ts, to prepend timestamp information to the standard output of another command. Useful for long-running processes where you’d like a historical record of what’s taking so long.
Piping anything to gnomon will prepend a timestamp to each line, indicating how long that line was the last line in the buffer—that is, how long it took the next line to appear. By default, gnomon will display the seconds elapsed between each line, but that is configurable.
How do you time how long a command took to run? [duplicate]
time will execute the rest of the command line as a command (in this example somecommand —what=argument ) and when the command is done it will print the elapsed time.
example output (if you are using bash):
$ time somecommand --what=argument . . (output of somecommand) . real 0m5,020s user 0m0,010s sys 0m0,010s
the information that you typically want is this line: real 0m5,020s . that means the command took about 5 seconds. for more information about the other numbers see here: https://stackoverflow.com/questions/556405/what-do-real-user-and-sys-mean-in-the-output-of-time1
time is a builtin command in most shells. the example output above is from the bash builtin. sometimes you will want to use the «system time «. for example when you need a consistent output format that is not dependent on the shell.
if you want to use the system time you have, among other, following options:
$ /usr/bin/time somecommand --what=islove
$ command time somecommand --what=isyourquest
there are more but that is outside the scope of this question and answer.
the command method works in bash and maybe some other shells. but might have different behaviour if used in scripts or functions or subshells or whatnot.
invoking the binary directly /usr/bin/time is probably the most safe and portable method to avoid the shell builtin time .
for more information on the difference of a shell builtin and a system command read here: What is the difference between a builtin command and one that is not?
example output using system time :
$ /usr/bin/time somecommand --what=argument . . (output of somecommand) . 0.00user 0.01system 0:06.02elapsed 0%CPU (0avgtext+0avgdata 3656maxresident)k 0inputs+0outputs (0major+1089minor)pagefaults 0swaps
the information that you typically want is 0:06.02elapsed . that means the command took about 6 seconds. for the meaning of the other numbers read the man page: http://man7.org/linux/man-pages/man1/time.1.html
you can change the output of the system time . use -p to get output similar to the shell builtin time :
$ /usr/bin/time -p sleep 1.5 real 1.50 user 0.00 sys 0.00
use -f to write your own format:
$ /usr/bin/time -f %E sleep 1.5 0:01.50
%E is the «elapsed» part. the part you are usually most interested in.
how to redirect or capture the output
for demonstration observe command hellostdoutstderr :
#!/bin/sh sleep 0.5 echo stdout echo stderr >&2
$ ./hellostdoutstderr stdout stderr
capture stdout and stderr separately
$ ./hellostdoutstderr >stdout 2>stderr $ cat stdout stdout $ cat stderr stderr
the system time prints to stderr so it is captured in the stderr redirect
$ /usr/bin/time ./hellostdoutstderr >stdout 2>stderr $ cat stdout stdout $ cat stderr stderr 0.00user 0.00system 0:00.50elapsed 1%CPU (0avgtext+0avgdata 3672maxresident)k 0inputs+16outputs (0major+311minor)pagefaults 0swaps
you can tell the system time to print to a separate file
$ /usr/bin/time -o timeout ./hellostdoutstderr >stdout 2>stderr $ cat stdout stdout $ cat stderr stderr $ cat timeout 0.00user 0.00system 0:00.50elapsed 1%CPU (0avgtext+0avgdata 3676maxresident)k 0inputs+16outputs (0major+309minor)pagefaults 0swaps
the bash builtin time always prints to the terminal even if stdout and stderr is redirected. this is possible because it is a builtin and can do whatever it likes (in the shell)
$ time ./hellostdoutstderr >stdout 2>stderr real 0m0,511s user 0m0,005s sys 0m0,006s
stdout and stderr are captured but bash builtin time still prints to shell. it is possible to capture the output of the bash builtin time but why fight bash if it is easier to use system time ( /usr/bin/time ).
to time more complex commands you have severals options
if you just want to time two command one after the other
$ time sh -c ' complex command chain '
but mind the quoting and other shenanigans. better put the commands in a script and time the script: