Linux time real user sys

Команда time в Linux

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

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

Версии Time Command

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

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

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

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

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

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

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

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

Выводы

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

Источник

Linux time command — real vs user vs system

I am running a jar file in Linux with time command. Below is the output after execution.

Below is the command executed.

But actual time taken to execute the process is 9270 seconds.

Why the actual time(wall clock time) and real time is different?

Can anyone explain this? Its running on multi core machine (32 core).

2 Answers 2

Maybe this explains the deviation you are experiencing. From the time Wikipedia article:

Because a program may fork children whose CPU times (both user and sys) are added to the values reported by the time command, but on a multicore system these tasks are run in parallel, the total CPU time may be greater than the real time.

Apart from that, your understanding of real time conforms with the definition given in time(7) :

Real time is defined as time measured from some fixed point, either from a standard point in the past (see the description of the Epoch and calendar time below), or from some point (e.g., the start) in the life of a process (elapsed time).

See also bash(1) (although its documentation on the time command is not overly comprehensive).

Читайте также:  Телефоны sony с windows

If seconds are exact enough for you, this little wrapper can help:

Note: If the system time is changed while your program is running, the results will be incorrect.

Источник

Should I use «real» or «user+sys» on the time function?

I understand the difference between «real»,»user» and «sys» when you use the time command on Linux, as explained on this other thread: What do ‘real’, ‘user’ and ‘sys’ mean in the output of time(1)?

Now I am working on a small comparison between the performance of Python, Java and C, and I am wondering which report I should use.

«User+sys» seems to be the more realistic one, but wouldn’t this cause problems when comparing C to Java, for instance, cause the JVM knows how to optimize the code for multi-processors/threads while GCC doesn’t?

Also, wouldn’t «real» be realistic enough if I make sure no other heavy process is running on the background?

1 Answer 1

The answer will depend on what you mean by «the performance of (Python|Java|C)». In many cases what a user really cares about is the elapsed wall time, corresponding to real . Suppose you write some piece of code in a reasonable way in several languages and one of the languages can automatically parallelize it to use your 4 cores. If this makes the user wait less time for a reply, then I say this is a fair comparison. Of course it is valid for that particular machine, the results on a single core machine could be different. If an app causes page faults, then it makes the user wait. For the user it’s no help if you say the app took fewer cycles if they have to wait longer.

Any way you measure, be sure to repeat the tests multiple times, as there can be lots of variation between runs. Languages like Java also need a program to run for some time before it reaches top speed, due to JIT compilation (but again: if your program is very short by definition and doesn’t allow the Java Virtual Machine to warp up, then well it’s too bad for Java). Testing performance is very tricky and even experienced developers are prone to misinterpreting results or measuring not what they really intended.

Источник

How to interpret time «real», «user» and «sys»

I’ve been fine-tuning code to reduce processing from 30 seconds to under a second in various parts of my bash program. I’m having trouble wrapping my mind about how the time command works when it reports real , user and sys variables.

I have this code:

That reports this:

Why is sys time reporting zero?

Interpreting the output of time builtin command one would assume the system is doing nothing but surely this isn’t what is happening?

ps I know \n can be used as a new-line to echo with -e parameter. My habit is to sacrifice one liner-cuteness and fringe arguments in favor of readability.

1 Answer 1

Long story short, it simply means that your program didn’t request to perform any privileged tasks, hence CPU has spend no time in the privileged (kernel) mode.

Читайте также:  Microsoft windows system32 rundll32 exe

Basics First

First of all, there’s several things you need to understand in order to interpret the output of time properly:

  • which time command you’re running (because there’s multiple)
  • the meaning of each field and what each one of them means (extra reading here)
  • the difference between kernel and user mode

There’s two types time command. There’s shell built-in and there’s /usr/bin/time . The shell built in is the one that you’re using and it defaults to showing 3 lines, real , user ,and sys . The manual for time also mentions this same form of output:

And if you check the «FORMATTING THE OUTPUT» section we have:

From all this info we can gather that there’s two modes in which CPU can run — user mode and kernel mode, and the time command displays how long CPU remains in a given mode to do whatever your program/app has asked CPU to do.

Understanding what is sys time reporting and what does 0 value mean

OK, so we understand the difference is that there’s user mode and kernel mode in which code can run. We already can figure that this basically means the program didn’t use kernel mode for executing some tasks. What does that actually mean ?

In Kernel mode, the executing code has complete and unrestricted access to the underlying hardware. It can execute any CPU instruction and reference any memory address.

And from another answer on the same post:

The switch from user mode to kernel mode is not done automatically by CPU. CPU is interrupted by interrupts (timers, keyboard, I/O). When interrupt occurs, CPU stops executing the current running program, switch to kernel mode, executes interrupt handler. This handler saves the state of CPU, performs its operations, restore the state and returns to user mode.

So that’s what your output means — there was no switch to kernel mode and CPU did not receive any interrupts from the program to do so. This also means that your code doesn’t have anything that would require elevated privileges from CPU

Note: this probably should be rephrased as «there was no long/noticeable switch into kernel mode», since allocating memory with something like malloc() function in C would require switching into kernel mode, but these are microscopic switches, which we’d really have to investigate with a debugger or strace command.

Источник

Как найти время выполнения команды или процесса в Linux

Вероятно, вы знаете время начала команды / процесса и как долго процесс выполняется в Unix-подобных системах.

Но когда вы его закончили и / или какое общее время, затраченное на выполнение команды / процесса?

В Unix-подобных системах есть утилита с именем «GNU time», специально предназначенная для этой цели.

Используя утилиту Time, мы можем легко измерить общее время выполнения команды или программы в операционных системах Linux.

Хорошо, что команда «Time» поставляется в большинстве дистрибутивов Linux, поэтому вам не нужно беспокоиться об установке.

Найти время выполнения команды или процесса в Linux

Чтобы измерить время выполнения команды / программы, просто запустите.

Вышеуказанные команды отображают общее время выполнения команды «ls».

Замените «ls» любой командой / процессом по вашему выбору, чтобы найти общее время выполнения.

  • real – возвращает общее время, затраченное командой / программой,
  • user – указывает время, затраченное программой в пользовательском режиме,
  • sys – указывает время, затраченное программой в режиме ядра.
Читайте также:  Compiling from source windows

time и /usr/bin/time

Как вы могли заметить, в приведенных выше примерах мы использовали две команды «time» и «/usr/bin/time».

Итак, вы можете задаться вопросом, в чем разница между ними.

Сначала давайте посмотрим, что на самом деле «timeя» использует команду «type».

Для тех, кто не знает, команда Type используется для получения информации о команде Linux.

Как видите time – две штуки

  • Ключевое слово, встроенное в оболочку BASH
  • Исполняемый файл – /usr/bin/time

Поскольку ключевые слова оболочки имеют приоритет над исполняемыми файлами, когда вы просто запускаете runmimommand без полного пути, вы запускаете встроенную команду оболочки.

Но, когда вы запускаете /usr/bin/time, вы запускаете реальную программу времени GNU time.

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

Встроенное ключевое слово оболочки «time» доступно в большинстве оболочек, таких как BASH, ZSH, CSH, KSH, TCSH и т. д.

Ключевое слово оболочки «time» имеет меньше опций, чем исполняемые файлы.

Единственный вариант, который вы можете использовать в ключе «time», – это -p.

Теперь вы знаете, как найти общее время выполнения данной команды / процесса, используя команду «time».

Хотите узнать немного больше об утилите «GNU time»? Читайте дальше!

Краткое введение в программу «GNU time»

Программа GNU time запускает команду / программу с заданными аргументами и суммирует использование системных ресурсов в качестве стандартного вывода после завершения команды.

В отличие от ключевого слова time, программа GNU time не просто отображает время, используемое командой / процессом, но и другие ресурсы, такие как память, вызовы ввода-вывода и IPC.

Типичным синтаксисом команды Time является:

options в приведенном выше синтаксисе ссылаются на набор флагов, которые могут использоваться командой time для выполнения определенной функциональности.

Список доступных опций приведен ниже^

  • -f, -format – Используйте этот параметр, чтобы указать формат вывода по вашему желанию.
  • -p, -portability – Использовать переносимый формат вывода.
  • -o file, -output = FILE – Записывает вывод в FILE вместо отображения в качестве стандартного вывода.
  • -a, -append – Добавить файл в файл вместо перезаписывания.
  • -v, -verbose – Этот параметр отображает подробное описание вывода утилиты «время».
  • -Quiet – этот параметр запрещает утилиту времени «время» сообщать о статусе программы.
  • При использовании программы «GNU time» без каких-либо параметров вы увидите вывод, как показано ниже.

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

В некоторых случаях вы можете записать вывод использования системного ресурса в файл, а не отображать его в терминале. Для этого используйте флаг -o, как показано ниже.

Как вы можете видеть на выходе, утилита Time не отображает результат. Потому что мы записываем вывод в файл с именем file.txt. Давайте посмотрим на этот файл:

Когда вы используете флаг -o, если нет файла с именем «file.txt», он будет создавать и записывать вывод в него.

Если файл.txt уже присутствует, он перезапишет его содержимое.

Вы также можете добавить вывод в файл, а не переписывать его, используя флаг -a.

Флаг -f позволяет пользователям управлять форматом вывода по своему усмотрению.

Скажем, например, следующая команда отображает вывод команды «ls» и показывает только пользователя, систему и общее время.

Помните, что встроенная команда «time» не поддерживает все функции программы GNU time.

Для получения дополнительной информации о утилите времени GNU см. Справочные страницы.

Источник

Оцените статью