Linux top cpu usage

Загрузка процессора Linux

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

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

Как посмотреть загрузку процессора в Linux

1. Утилита htop

Самый простой способ узнать насколько процессор загружен в данный момент — воспользоваться утилитой htop. Она показывает не только процент загрузки по каждому ядру процессора отдельно, но и позволяет найти процессы, которые нагружают систему больше всего. Для установки htop в Debian или Ubuntu выполните:

sudo apt install htop

А в CentOS или REHL:

sudo yum install htop

Главное окно программы выглядит вот так:

Здесь в верхней части окна выводится загрузка ядер процессора в виде наглядных шкал, а ниже процессы. В данном примере у процессора 12 ядер и каждое из них загружено не больше чем на один процент.

2. Файл /proc/loadavg

Если надо сориентироваться какая была нагрузка на процессор в последнее время, тут htop не поможет. Можно воспользоваться файлом /proc/loadavg. Его создаёт ядро и в нём содержится информация о средней нагрузке за одну, пять и пятнадцать минут. Но обратите внимание, данные, находящиеся в этом файле не такие однозначные. Во первых, это не проценты, во вторых, они отображают не нагрузку на процессор, а нагрузку на систему в целом.

Первые три значения в этом файле означают среднее количество процессов или потоков, которые выполняются, находятся в очереди на выполнение или ждут завершения операций ввода/вывода за 1, 5 и 15 минут. Вот:

Обычно, если значение больше единицы — значит нагрузка уже большая и надо разбираться почему. Если значение за минуту меньше значений за пять и пятнадцать минут — нагрузка падает, если больше — растёт. Таким образом можно немного сориентироваться насколько загружена ваша система. Эти значения можно использовать для общего ориентирования или отправки уведомлений на почту, а для разбора полётов уже применять другие метрики и программы.

Четвертое значение здесь — это количество процессов — выполняемых в данный момент, обычно соответствует количеству процессоров, следующее число через слеш — это общее количество таких процессов в системе. Последнее значение — PID последнего созданного процесса.

3. Утилита mpstat

Утилита mpstat позволяет посмотреть подробную статистику по использованию процессора. Можно посмотреть не только информацию по каждому из ядер, но и куда используются ресурсы — на ввод/вывод, ядро или программы пространства пользователя. Для установки программы в Ubuntu или Debian выполните:

sudo apt install sysstat

В CentOS или REHL:

sudo yum install sysstat

Для просмотра общей информации выполните такую команду:

А для просмотра подробностей по каждому ядру процессора используйте опцию -P с параметром ALL:

Вот значения колонок в выводе этой программы:

  • CPU — номер ядра процессора;
  • %usr — потребление программами пространства пользователя;
  • %nice — потребление ресурсов в процентах программами в пространстве пользователя с повышенным приоритетом;
  • %sys — потребление ресурсов процессора ядром;
  • %iowait — затраты на ожидание ввода/вывода;
  • %irq — ресурсы, потраченные на прерывания для работы с аппаратным обеспечением;
  • %soft — ресурсы, потраченные на программные прерывания;
  • %steal — украденные процессорные ресурсы, актуально для виртуальных машин;
  • %guest — ресурсы, потраченные на работу виртуального процессора;
  • %idle — неиспользованные ресурсы.
Читайте также:  Vim для linux как установить

Как видите, в данном случае нагрузка на процессор не достигает даже трех процента для некоторых ядер.

4. Команда nmon

Утилита nmon позволяет выводить данные, в виде, похожем на htop, но только немного подробнее. Для установки её в Ubuntu и Debian выполните:

sudo apt install nmon

Для установки в CentOS или REHL:

sudo yum install nmon

После запуска надо нажать кнопку c для того чтобы отобразить информацию о нагрузке на ядра процессора:

Здесь кроме наглядной шкалы по каждому ядру выводится информация в процентах по таким показателям:

  • User% — ресурсы, потраченные программами в пространстве пользователя;
  • Sys% — ресурсы, потраченные ядром;
  • Wait% — ресурсы, которые идут на ожидание ввода/вывода;

Здесь уже можно сориентироваться насколько всё загружено и в чём проблема.

5. CoreFreq

Если всей полученной ранее информации о производительности вам мало, можно воспользоваться утилитой CoreFreq. Её нет в официальных репозиториях, поэтому придется собирать программу из исходников. Но зато она имеет свой модуль ядра, который устанавливает свои счетчики производительности в ядре и возвращает утилите наиболее подробные данные. Сначала установите необходимые компоненты. В Ubuntu:

sudo apt install dkms git libpthread-stubs0-dev

В CentOS или REHL:

sudo yum group install ‘Development Tools’

Затем скачайте репозиторий утилиты с GitHub и соберите её:

git clone https://github.com/cyring/CoreFreq.git

Загрузите модуль ядра такой командой:

sudo insmod corefreqk.ko

Запустите её сервис:

Затем запускайте программу:

Вверху программы отображается информация о процессоре, ниже шкалы с загруженностью каждого ядра, а её ниже различные показатели по каждому ядру: частота — Freq, ускорение — Turbo, C0-C7 — значения состояний C-State процессора. В данном примере, большинство ядер процессора работают на минимальной частоте и большую часть времени находятся в состоянии C1. Это состояние означает, что ядро не активно, но может в любой момент перейти к выполнению инструкций. Состояние C0 — означает, что ядро активно и выполняет какие-то действия.

С помощью этой утилиты вы сможете узнать максимально подробную информацию о загрузке процессора и о самом процессоре в целом.

Выводы

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

Источник

How Do I Find Out Linux CPU Utilization?

W henever a Linux system CPU is occupied by a process, it is unavailable for processing other requests. Rest of pending requests must wait until the CPU is free. This becomes a bottleneck in the system. Following command will help you to identify CPU utilization, so that you can troubleshoot CPU-related performance problems on a Linux-based system. This page explains how to check Linux CPU utilization and usage using various tools.

Finding CPU utilization is one of the important tasks. Linux comes with various utilities to report CPU utilization. With these commands, you will be able to find out:

  1. CPU utilization
  2. Display the utilization of each CPU individually (SMP cpu)
  3. Find out your system’s average CPU utilization since the last system reboot
  4. Determine which process is eating the CPU(s)

The old good top command to find out Linux CPU Utilization

The top program provides a dynamic real-time view of a running system. It can display system summary information as well as a list of tasks currently being managed by the Linux kernel. The top command monitors CPU utilization, process statistics, and memory utilization. The top section contains information related to overall system status – uptime, load average, process counts, CPU status, and utilization statistics for both memory and swap space.

Читайте также:  При установке linux что такое размер установки

Top command to find out Linux cpu usage

Type the top command:
$ top

Say hello to htop

htop is similar to top command but allows you to scroll vertically and horizontally and much more.
htop

Find Linux CPU utilization using mpstat and other tools

Please note that you need to install a special package called sysstat to take advantage of following commands. This package includes system performance tools for Linux (Red Hat Linux / RHEL includes these tools by default). Install it on a Debian or Ubuntu Linux using apt-get command/apt command:
# apt-get install sysstat
Use up2date command if you are using RHEL/CentOS Linux v4.x or older:
# up2date install sysstat
Run yum command command if you are using a CentOS/RHEL/Oracle Linux v5.x+ or newer:
# yum install sysstat
Fedora users should run the dnf command:
# dnf install sysstat

Display the utilization of each CPU individually using mpstat

If you are using SMP (Multiple CPU) system, use mpstat command to display the utilization of each CPU individually. It report processors related statistics. For example, type command:
# mpstat
Sample outputs:

The mpstat command display activities for each available processor, processor 0 being the first one. Global average activities among all processors are also reported. The mpstat command can be used both on SMP and UP machines, but in the latter, only global average activities will be printed.:
# mpstat -P ALL
Sample outputs:

Another output from my Ubuntu 18.04 LTS server:

Report CPU utilization using the sar command

You can display today’s CPU activity, with the help of sar command:
# sar
Output:

Comparison of CPU utilization

The sar command writes to standard output the contents of selected cumulative activity counters in the operating system. The accounting system, based on the values in the count and interval parameters. For example display comparison of CPU utilization; 2 seconds apart; 5 times, use:
# sar -u 2 5
Output (for each 2 seconds. 5 lines are displayed):

  • -u 12 5 : Report CPU utilization. The following values are displayed:
    • %user: Percentage of CPU utilization that occurred while executing at the user level (application).
    • %nice: Percentage of CPU utilization that occurred while executing at the user level with nice priority.
    • %system: Percentage of CPU utilization that occurred while executing at the system level (kernel).
    • %iowait: Percentage of time that the CPU or CPUs were idle during which the system had an outstanding disk I/O request.
    • %idle: Percentage of time that the CPU or CPUs were idle and the system did not have an outstanding disk I/O request.

To get multiple samples and multiple reports set an output file for the sar command. Run the sar command as a background process using.
# sar -o output.file 12 8 >/dev/null 2>&1 &
Better use nohup command so that you can logout and check back report later on:
# nohup sar -o output.file 12 8 >/dev/null 2>&1 &

All data is captured in binary form and saved to a file (data.file). The data can then be selectively displayed ith the sar command using the -f option.
# sar -f data.file

  • 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

Task: Find out who is monopolizing or eating the CPUs

Finally, you need to determine which process is monopolizing or eating the CPUs. Following command will displays the top 10 CPU users on the Linux system.
# ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10
OR
# ps -eo pcpu,pid,user,args | sort -r -k1 | less
Sample outputs:

Now you know vmware-vmx process is eating up lots of CPU power. The ps command command displays every process ( -e ) with a user-defined format ( -o pcpu ). First field is pcpu (cpu utilization). It is sorted in reverse order to display top 10 CPU eating process.

iostat command

You can also use iostat command which report Central Processing Unit (CPU) statistics and input/output statistics for devices and partitions. It can be use to find out your system’s average CPU utilization since the last reboot.
# iostat Output:

You may want to use following command, which gives you three outputs every 5 seconds (as previous command gives information since the last reboot): $ iostat -xtc 5 3

vmstat command

The vmstat command shows information about processes, memory, paging, block IO, traps, disks and cpu activity. Run vmstat as follows:
vmstat
vmstat [options] vmstat [interval] [count]
Sample outputs:

In this example, run vmstat with an interval of one second twenty one times:
vmstat 1 21

How to interpret vmstat CPU section output

These are percentages of total CPU time.

  1. us : Time spent running non-kernel code. (user time, including nice time)
  2. sy : Time spent running kernel code. (system time)
  3. id : Time spent idle.
  4. wa : Time spent waiting for IO.
  5. st : Time stolen from a virtual machine.

turbostat command

The turbostat command shows processor topology, frequency, idle power-state statistics, temperature and power on X86 processors. Simply run as follows:
sudo turbostat
sudo turbostat 5
See turbostat man page for further details.

nmon command

nmon is a systems administrator tool to get information about cpu, top process, memory and much more. One can install it as follows:
sudo apt install nmon ## Debain/ubuntu ##
sudo dnf install nmon ## fedora ##
sudo yum install nmon ## centos/rhel ##
Now start it:
nmon

GUI tools for your laptops/desktops

Above tools/commands are quite useful on remote server. For local system with X GUI installed you can try out gnome-system-monitor. It allows you to view and control the processes running on your system. You can access detailed memory maps, send signals, and terminate the processes.
$ gnome-system-monitor
Sample outputs:

In addition, the gnome-system-monitor provides an overall view of the resource usage on your system, including memory and CPU allocation:

Finding out Linux CPU usage using GUI tool

Conclusion

This page explained various Linux command line tools that we can use to find Linux CPU utilization. For further information, see the following resources:

Источник

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