Linux usr bin time

Linux / Unix: time Command Examples

I am new Linux and Unix systems user. How do I display the time of the execution of a command/script on Linux or Unix-like operating systems using shell prompt?

You need to use the time command to display the elapsed time during the execution of a command or script. This page explains time command in Linux and Unix-like system with most common examples.

time command details
Description Report time consumed by command execution
Category Processes Management
Difficulty Easy
Root privileges No
Est. reading time 4 minutes
Table of contents
  • » Syntax
  • » Examples
  • » Redirect time output to file
  • » GNU/Linux time command
  • » Understanding TIMEFORMAT
  • » Summing up
  1. real time
  2. user time
  3. sys time

Purpose

Run command/programs or script and summarize system resource usage on your screen.

Syntax

The basic syntax is as follows:
time command
time command arg1 arg2 . argN
time [options] command arg1 arg2 . argN

Is my time command shell built-in or external command?

The time command is also built into the BASH/KSH/CSH/TCSH with a different syntax. Let us use the type command or command command to verify location:
type -a time
command -V time

To run the time command while in the shells, type:
/usr/bin/time -p command
/bin/time -p command arg1 arg2
Users of the bash or ksh shell need to use an explicit path in order to run the external time command and not the shell builtin variant.

time command examples

To measure the time required to run a program called date, enter:
$ time date
To use external time command give full path to time binary:
$ /usr/bin/time -p date

How do I redirect time command output to a file?

The syntax is as follows to save a record of the time command information in a file called output.time.txt, run:

If above command failed, try the following to save a record of the time command information in a file:

Use the cat command to display output on screen:
$ cat output.time.txt

A note about GNU/Linux time command

GNU/Linux user can use the following syntax to write the resource use statistics to file instead of to the standard error stream:
$ /usr/bin/time -o output.time.txt -p date
$ cat output.time.txt
Pass the -a option to append the resource use information to the output file instead of overwriting it. This option is only useful with the -o option:
$ /usr/bin/time -a -o output.time.txt -p sleep 2
$ cat output.time.txt

Using time command on my Linux system

Use FORMAT as the format string that controls the output of time

Table 1: Formatting the output of /usr/bin/time
FORMAT Description
% A literal `%’.
C Name and command line arguments of the command being timed.
D Average size of the process’s unshared data area, in Kilobytes.
E Elapsed real (wall clock) time used by the process, in [hours:]minutes:seconds.
F Number of major, or I/O-requiring, page faults that occurred while the process was running. These are faults where the page has actually migrated out of primary memory.
I Number of file system inputs by the process.
K Average total (data+stack+text) memory use of the process, in Kilobytes.
M Maximum resident set size of the process during its lifetime, in Kilobytes.
O Number of file system outputs by the process.
P Percentage of the CPU that this job got. This is just user + system times divided by the total running time. It also prints a percentage sign.
R Number of minor, or recoverable, page faults. These are pages that are not valid (so they fault) but which have not yet been claimed by other virtual pages. Thus the data in the page is still valid but the system tables must be updated.
S Total number of CPU-seconds used by the system on behalf of the process (in kernel mode), in seconds.
U Total number of CPU-seconds that the process used directly (in user mode), in seconds.
W Number of times the process was swapped out of main memory.
X Average amount of shared text in the process, in Kilobytes.
Z System’s page size, in bytes. This is a per-system constant, but varies between systems.
c Number of times the process was context-switched involuntarily (because the time slice expired).
e Elapsed real (wall clock) time used by the process, in seconds.
k Number of signals delivered to the process.
p Average unshared stack size of the process, in Kilobytes.
r Number of socket messages received by the process.
s Number of socket messages sent by the process.
t Average resident set size of the process, in Kilobytes.
w Number of times that the program was context-switched voluntarily, for instance while waiting for an I/O operation to complete.
x Exit status of the command.

Using time command on Linux or Unix with formatting

In this example, show just the user, system, and total time using format option:
$ /usr/bin/time -f «%E real,%U user,%S sys» sleep 2
$ /usr/bin/time -f «%E real,%U user,%S sys» /path/to/script
Sample outputs:

See percentage of CPU used by your command:
/usr/bin/time -f «CPU Percentage: %P» command
/usr/bin/time -f «CPU Percentage: %P» grep vivek /etc/passwd
/usr/bin/time -f «CPU Percentage: %P» find /etc/ -type f -iname «a*.conf»
CPU Percentage: 76%

Understanding TIMEFORMAT used by bash’s buitin time

The value of TIMEFORMAT parameter is used as a format string specifying how the timing information for pipelines prefixed with the time reserved word should be displayed. The % character introduces an escape sequence that is expanded to a time value or other information. The escape sequences and their meanings are as follows; the braces denote optional portions.

Table 2: TIMEFORMAT parameter values

Value Description
%% A literal %.
%[p][l]R The elapsed time in seconds.
%[p][l]U The number of CPU seconds spent in user mode.
%[p][l]S The number of CPU seconds spent in system mode.
%P The CPU percentage, computed as (%U + %S) / %R.

The optional p is a digit specifying the precision, the number of fractional digits after a decimal point. A value of 0 causes no decimal point or fraction to be output. At most three places after the decimal point may be specified; values of p greater than 3 are changed to 3. If p , is not specified, the value 3 is used. The optional l specifies a longer format, including minutes, of the form MMmSS.FFs . The value of p determines whether or not the fraction is included.

How to use bash’s builtin time command in Linux / Unix

The syntax is almost same:
time command
time ls
TIMEFORMAT=»%P» time ls
TIMEFORMAT=»%U» time sleep 3
TIMEFORMAT=»%S» time sleep 3
TIMEFORMAT=»%R» time sleep 2

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Summing up

You learned about the time command that reports the time consumed by the pipeline’s execution. It will summarize system resource usage on the screen. The syntax of time might change on your local Unix or Linux distro. Hence, to get help for builtin time command, type:
help time
# or read shell man page
man bash
For external time (/bin/time or /usr/bin/time) command, run:
man time

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Про Debian

Для анализа того, сколько будут работать написанные мною скрипты я частенько использовал утилиту time. По крайней мере, я думал, что использовал утилиту time.
Как оказалось, в bash’e есть одноименная встроенная функция, которая представляет из себя сильно урезанный аналог настоящей утилиты time. Открыв однажды man time я немного удивился и навсегда запомнил этот момент.

Собственно, в чём соль. Из bash-евого time мы можем узнать по сути только время, которое было потрачено на выполнение команды системой. Да, пытливый ум почерпнет там несколько больше информации, но всё равно её набор сильно ограничен тремя строчками. Собственно:

$ time ls
.
real 0m0.011s
user 0m0.000s
sys 0m0.000s

Ну да, ценная информация. Но оригинальная утилита time была написана для того, чтобы можно было посмотреть сколько ресурсов заняло у системы выполнение команды. При том любых ресурсов.
В частности, ресурсы процессора, память, операции ввода-вывода, количество swap-событий и тучу другой диагностической информации, вплоть до exit-кода.
Такой мощный инструмент уже намного лучше подходит для диагностики ресурсоёмкости. Описывать заново мануал я вам не собираюсь (в man time можно подсмотреть все ресурсы, которые оно может подсчитывать), а попробую просто вкратце описать, как её использовать. А главное — развеять один из мифов тех линуксоидов, который пришли к нам уже во владения bash’a и ничего другого не видели =)

Начнем с самого простого, научимся её запускать:

$ /usr/bin/time ls
.
0.01user 0.00system 0:00.01elapsed 100%CPU (0avgtext+0avgdata 5024maxresident)k
0inputs+0outputs (0major+382minor)pagefaults 0swaps

Или так(все же помнят, что если перед командой поставить back-слэш, то bash сразу полезет искать бинарник в $PATH, игнорируя конфиг с алиасами и встроенные функции?):

$ \time ls
.
0.01user 0.00system 0:00.01elapsed 100%CPU (0avgtext+0avgdata 5024maxresident)k
0inputs+0outputs (0major+382minor)pagefaults 0swaps

time (в любой вариации) выводит себя любимого на STDERR. Нагло воспользуемся этим, чтобы не наблюдать на экране мусор от вывода:

$ \time cat /dev/urandom 1>/dev/null
^CCommand terminated by signal 2
0.00user 1.14system 0:01.14elapsed 99%CPU (0avgtext+0avgdata 2544maxresident)k
0inputs+0outputs (0major+206minor)pagefaults 0swaps

Здесь видно, что на экран попало только сообщение о том, что команда была прервана по ^C, и вывод утилиты time.

Ну и перейдем к самому важному. К формату вывода. Самое ценное для нас, что умеет \time — вывести реальное физическое время, которое прошло с момента запуска команды до момента её выполнения (по крайней мере, нам об этом говорит название утилиты =) ):

$ \time -f %E ls 1>/dev/null
0:00.01

$ \time -f %E sleep 5 1>/dev/null
0:05.00

-f %E — задало формат вывода для time. E = реальное время, % — метасимвол. Остальные переменные, опять же, есть в мане.
Ну и попробуем чуть более сложный формат, чтобы уметь с ним работать:

$ \time -f «Command: %C \nExit code: %X \nReal time: %E» sleep 1 1>/dev/null
Command: sleep 1
Exit code: 0
Real time: 0:01.00

Источник

Команда time в Linux

Например, если у вас есть два разных скрипта, выполняющих одну и ту же работу, и вы хотите знать, какой из них работает лучше, вы можете использовать команду time в Linux для определения продолжительности выполнения каждого скрипта.

Версии команды time

И Bash, и Zsh, наиболее широко используемые оболочки Linux, имеют свои собственные встроенные версии команды time, которые имеют приоритет над командой Gnu time.

Вы можете использовать команду type, чтобы определить, является ли время двоичным или встроенным ключевым словом.

Чтобы использовать команду time в Gnu, вам нужно указать полный путь к двоичному файлу time, обычно /usr/bin/time используйте команду env или начальную обратную косую черту \time которая предотвращает использование обеих и встроенных функций.

Время Gnu позволяет вам форматировать выходные данные и предоставляет другую полезную информацию, такую ​​как память ввода-вывода и IPC-вызовов.

Использование команды Time в Linux

В следующем примере мы собираемся измерить время, необходимое для загрузки ядра Linux, с помощью инструмента wget:

То, что будет напечатано как вывод, зависит от версии команды time, которую вы используете:

  • реальное или общее или прошедшее (время настенных часов) – это время от начала до конца вызова. Это время от момента нажатия клавиши Enter до момента завершения команды wget.
  • user – количество процессорного time, проведенного в пользовательском режиме.
  • system или sys – количество процессорного time, проведенного в режиме ядра.

Заключение

К настоящему time вы должны хорошо понимать, как использовать команду time.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Источник

Читайте также:  Command line debugging windows
Оцените статью