What is iostat in linux

iostat command in Linux with examples

The iostat command in Linux is used for monitoring system input/output statistics for devices and partitions. It monitors system input/output by observing the time the devices are active in relation to their average transfer rates. The iostat produce reports may be used to change the system configuration to raised balance the input/output between the physical disks. iostat is being included in sysstat package. If you don’t have it, you need to install first.

Command to install on different Distros:

  • On RedHat / CentOS / Fedora
  • On Debian / Ubuntu / Linux Mint

Note: 10 Linux iostat Command to Report CPU and I/O Statistics are listed below:

  • iostat: Get report and statistic.
  • iostat -x: Show more details statistics information.
  • iostat -c: Show only the cpu statistic.
  • iostat -d: Display only the device report.
  • iostat -xd: Show extended I/O statistic for device only.
  • iostat -k: Capture the statistics in kilobytes or megabytes.
  • iostat -k 2 3: Display cpu and device statistics with delay.
  • iostat -j ID mmcbkl0 sda6 -x -m 2 2: Display persistent device name statistics.
  • iostat -p: Display statistics for block devices.
  • iostat -N: Display lvm2 statistic information.

1) iostat Command: The iostat command in linux is used to get report and statistic.

Syntax:

Example: Here’s a sample.

The first section contains CPU report:

  • %user : It shows the percentage of CPU being utilization that while executing at the user level.
  • %nice : It shows the percentage of CPU utilization that occurred while executing at the user level with a nice priority.
  • %system : It shows the percentage of CPU utilization that occurred while executing at the system (kernel) level.
  • %iowait : It shows the percentage of the time that the CPU or CPUs were idle during which the system had an outstanding disk I/O request.
  • %steal : It shows the percentage of time being spent in involuntary wait by the virtual CPU or CPUs while the hypervisor was servicing by another virtual processor.
  • %idle : It shows the percentage of time that the CPU or CPUs were idle and the system did not have an outstanding disk I/O request.

The second section of the output contains device utilization report:

  • Device : The device/partition name is listed in /dev directory.
  • tps : The number of transfers per second that were issued to the device. Higher tps means the processor is busier.
  • Blk_read/s : It shows the amount of data read from the device expressed in a number of blocks (kilobytes, megabytes) per second.
  • Blk_wrtn/s : The amount of data written to the device expressed in a number of blocks (kilobytes, megabytes) per second.
  • Blk_read : It shows the total number of blocks read.
  • Blk_wrtn : It shows the total number of blocks written.

iostat uses files mentioned below to create the reports:

  • /proc/stat Contains the system statistics.
  • /proc/uptime Contains the system uptime.
  • /proc/diskstats Contains the disks statistics.
  • /sys Contains the statistics for block devices.
  • /proc/self/mountstats Contains the statistics for network filesystems.
  • /dev/disk Contains the persistent device names.
Читайте также:  Приложения для линукс смарт

2) iostat -x Command: This command shows more details statistics information. iostat command gives I/O devices report utilization as a result. So it’s possible to extend the statistic result for a diagnose in depth with the -x option.

Syntax:

Example:

  • avg-cpu: It tells us the cpu block information.
  • Devide: It tells us the device block information. To be sure that you are on the good device.
  • %util: It tells us that how much time did the storage device have outstanding work (was busy).
  • svctm: It indicates how fast does your I/O subsystem respond requests overall when busy. Actually, the less you load your system, higher svctm is.
  • await: It indicates how fast do requests go through. It is just an average.
  • avgqu-sz: It tells us how many requests are there in a request queue. Low = either your system is not going to be loaded, or has serialized I/O and cannot utilize underlying storage properly. High = your software stack is scalable enough to be loaded properly underlying I/O.
  • avgrq-sz: It’s just an average request size which can indicate what kind of workload happens.
  • wsec/s & rsec/s: It tells us the sectors read and written per second. Divide by 2048, and you’ll get the megabytes per second.
  • r/s & w/s: It tells us read and write requests per second. These numbers are the ones that are the I/O capacity figures, though of course, depending on how much pressure underlying I/O subsystem gets (queue size!), they can vary.
  • rrqm/s & wrqm/s: It tells us how many requests were merged by block layer.

3) iostat -c Command: This command show only the CPU statistic. It is possible to show the statistic information and report of our cpu with -c option.

Syntax:

Example:

4) iostat -d Command: This command displays only the device report. It is possible to only show the status of the device utilization with the help of -d option. It will be going to list information for each connected device.

Syntax:

Example:

5) iostat -xd Command: This command shows us the extended I/O statistic for device only. We can display extended the statistic on one side and from the other side we can display the extended statistics. It means that we can display the extended statistics only for devices with the help of -xd option as below:

Syntax:

Example:

6) iostat -k Command: This command captures the statistics in kilobytes or megabytes. By default, iostat measure the I/O system with the bytes unit. To make it easier to read, we can convert the iostat to show us reports in kilobytes or megabytes unit.

Читайте также:  Xml чем открыть mac os

Syntax:

Example:

7) iostat -m Command: Used to create a report with megabytes unit.

Syntax:

Example:

8) iostat -k 2 3 Command: This command displays CPU and device statistics with delay. Same with the vmstat, as a statistic tool is the best way to use it with delay parameter. With the delay, we can see that what’s the trend. Here are some of the samples to run iostat with delay.

Syntax:

Example:

9) iostat -c 2 2 Command: To show CPU only report with 2 seconds interval and 2 times reports.

Syntax:

Example:

10) iostat -d sda7 sda6 2 2 Command: To show sda6 and sda7 device only report with 2 seconds interval and 2 times reports.

Syntax:

Example:

11) iostat -j ID mmcbkl0 sda6 -x -m 2 2 Command: This command Display’s persistent device name statistics. It is possible to print the report by device name. Instead of the standard /dev/sda name, it will be going to print the persistent device name with -j parameter and adding ID keyword (specify the type of the persistent name).

Syntax:

Example:

12) iostat -p Command: This command display statistics for block devices. With the help of this command, it is possible to directly show information for each block device automatically. No need to indicate each of the device names. It will display statistics for block devices and all their partitions that are being used by the system. If a device name is entered on the command line, then the statistics for it and all of its partitions are displayed. Just use this -p option.

Syntax:

Example:

13) iostat -N Command: Display lvm2 statistic information. It is possible to view the LVM statistic with -N option. This command displays the registered device mapper names for any of the device mapper devices.

Источник

Описание iostat Linux

Утилита iostat позволяет проанализировать загруженность системы. Она выводит основные параметры ввода и вывода данных на диск, скорость записи и чтения данных, а также количество записанных или прочитанных данных. Кроме того, утилита выводит параметры загруженности процессора. Её можно использовать для оптимизации работы системы.

В этой статье мы рассмотрим как пользоваться iostat и что означают основные колонки в её выводе.

Описание iostat Linux

Синтаксис iostat очень простой. Вам достаточно выполнить:

$ iostat опции устройство интервал

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

  • — отобразить только информацию об использовании процессора;
  • -d — отобразить только информацию об использовании устройств;
  • -h — выводить данные в отчёте в удобном для чтения формате;
  • -k — выводить статистику в килобайтах;
  • -m — выводить статистику в мегабайтах;
  • -o JSON — выводить статистику в формате JSON;
  • -p — вывести статистику по устройству и всех его разделам;
  • -x — вывести расширенную статистику;
  • -y — отображать статистику с момента запуска утилиты, а не системы;
  • -z — спрятать информацию о дисках, у которых нет активности.
Читайте также:  Как отключить поддержку windows ink

Использование iostat в Linux

Самый простой пример использования утилиты, это запустить её без параметров. Она выведет отчёт с со средней статистикой с момента включения системы до момента запуска программы:

В первой части отчёта находится информация о загруженности процессора. Тут есть такие колонки:

  • %user — процент использования процессора программами, запущенными на уровне пользователя;
  • %nice — процент использования процессора программами запущенными тоже в пространстве пользователя, но только с изменённым приоритетом;
  • %system — процент использования процессора ядром;
  • %iowait — процент времени затраченного на ожидание завершения операций ввода/вывода;
  • %steal — процент простоя виртуального процессора, пока гипервизор отдаёт мощность другому виртуальному процессору;
  • %idle — процент времени пока процессор не занят ничем.

Если значение параметра %iowait слишком большое, то это может означать, что у вас проблема с производительностью диска и слишком много времени тратится на ожидание завершения ввода/вывода. Для устройств ввода/вывода тоже отображается ряд колонок с информацией. Разберемся что они означают:

  • tps — означает количество запросов на чтение или запись к устройству в секунду;
  • KB_read/s, MB_read/s — количество килобайт или мегабайт, прочитанных с устройства за секунду;
  • KB_wrtn/s, MB_wrtn/s — количество килобайт или мегабайт записанных на устройство в секунду;
  • KB_dscd/s, MB_dscd/s — скорость освобождения блоков данных на устройстве, килобайт или мегабайт в секунду;
  • KB_read, MB_read — общее количество прочитанных данных с диска с момента загрузки системы;
  • KB_wrtn, MB_wrtn — количество записанных данных с момента загрузки системы;
  • KB_dscd, MB_dscd — количество освобождённых блоков на диске в результате выполнения операции trim в килобайтах или мегабайтах.

С чтением и записью, я думаю, что всё понятно. Освобождение блоков с данными с помощью операции trim или discard актуально для SSD дисков. Этой операцией файловая система сообщает какие блоки больше хранить физически не нужно и можно использовать для других целей. Утилита отображает с какой скоростью эти блоки освобождаются, а также сколько блоков или мегабайт данных было освобождено. Рассмотрим ещё несколько примеров. Для просмотра данных в удобном формате выполните:

Чтобы посмотреть данные по нужному устройству просто укажите это устройство:

sudo iostat /dev/nvme0n1

Можно посмотреть статистику по каждому разделу устройства, тогда надо воспользоваться опцией -p:

sudo iostat -p /dev/nvme0n1

Чтобы утилита автоматически обновляла данные каждую секунду просто добавьте интервал. Например:

sudo iostat -p /dev/nvme0n1 1

Если вы не хотите чтобы утилита суммировала все данные с момента запуска операционной системы, то можно использовать опцию -y. Но работает она только если задан интервал:

sudo iostat -y -p /dev/nvme0n1 1

Выводы

В этой статье была рассмотрена команда iostat Linux. Она позволяет понять почему зависает ваша система и действительно ли причина этому — жёсткий диск. Мы рассмотрели далеко не все опции утилиты и далеко не все колонки из возможного её вывода. Более подробную информацию вы можете найти выполнив:

Самая свежая и достоверная информация, как правило, заполняется разработчиками и находится на man — страницах.

Источник

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