- How Do I Find Out Linux CPU Utilization?
- The old good top command to find out Linux CPU Utilization
- Top command to find out Linux cpu usage
- Say hello to htop
- Find Linux CPU utilization using mpstat and other tools
- Display the utilization of each CPU individually using mpstat
- Report CPU utilization using the sar command
- Comparison of CPU utilization
- Task: Find out who is monopolizing or eating the CPUs
- iostat command
- vmstat command
- How to interpret vmstat CPU section output
- turbostat command
- nmon command
- GUI tools for your laptops/desktops
- Conclusion
- 9 команд для проверки информации о CPU в Linux
- What specifically are wall-clock-time, user-cpu-time, and system-cpu-time in UNIX?
- 4 Answers 4
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:
- CPU utilization
- Display the utilization of each CPU individually (SMP cpu)
- Find out your system’s average CPU utilization since the last system reboot
- 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.
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.
- us : Time spent running non-kernel code. (user time, including nice time)
- sy : Time spent running kernel code. (system time)
- id : Time spent idle.
- wa : Time spent waiting for IO.
- 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:
Источник
9 команд для проверки информации о CPU в Linux
Информация об аппаратном обеспечении CPU
Информация о CPU (Central Processing Unit. Центральный процессор) включает в себя подробные сведения о процессоре, такие как архитектура, название производителя, модель, количество ядер, скорость каждого ядра и т.д.
В linux существует довольно много команд для получения подробной информации о CPU.
В этой статье мы рассмотрим некоторые из часто встречающихся команд, которые можно использовать для получения подробной информации о CPU.
1. /proc/cpuinfo
Файл /proc/cpuinfo содержит подробную информацию об отдельных ядрах CPU.
Выведите его содержимое с помощью less или cat .
Каждый процессор или ядро перечислены отдельно, а различные подробности о скорости, размере кэша и названии модели включены в описание.
Чтобы подсчитать количество процессоров, используйте grep с wc
Количество процессоров, показанное в /proc/cpuinfo, может не соответствовать реальному количеству ядер процессора. Например, процессор с 2 ядрами и гиперпоточностью будет показан как процессор с 4 ядрами.
Чтобы получить фактическое количество ядер, проверьте идентификатор ядра на наличие уникальных значений
Соответственно, есть 4 разных идентификатора ядра. Это указывает на то, что существует 4 реальных ядра.
2. lscpu — отображение информации об архитектуре CPU
lscpu — это небольшая и быстрая команда, не требующая никаких опций. Она просто выводит информацию об аппаратном обеспечении CPU в удобном для пользователя формате.
3. hardinfo
Hardinfo — это gui инструмент на базе gtk, который генерирует отчеты о различных аппаратных компонентах. Но он также может запускаться из командной строки, в случае если отсутствует возможность отображения gui (Graphical User Interface — графический интерфейс пользователя).
Он создаст большой отчет о многих аппаратных частях, читая файлы из каталога /proc. Информация о CPU находится в начале отчета. Отчет также может быть записан в текстовый файл.
Hardinfo выполняет несколько эталонных тестов, занимающих несколько минут, прежде чем вывести отчет на экран.
4. lshw
Команда lshw может отобразить ограниченную информацию о CPU. lshw по умолчанию показывает информацию о различных аппаратных частях, а опция ‘ -class ‘ может быть использована для сбора информации о конкретной аппаратной части.
Производитель, модель и скорость процессора отображаются правильно. Однако из приведенного выше результата невозможно определить количество ядер в процессоре.
Чтобы узнать больше о команде lshw, ознакомьтесь с этой статьей:
5. nproc
Команда nproc просто выводит количество доступных вычислительных блоков. Обратите внимание, что количество вычислительных блоков не всегда совпадает с количеством ядер.
6. dmidecode
Команда dmidecode отображает некоторую информацию о CPU, которая включает в себя тип сокета, наименование производителя и различные флаги.
7. cpuid
Команда cpuid собирает информацию CPUID о процессорах Intel и AMD x86.
Программа может быть установлена с помощью apt на ubuntu
А вот пример вывода
8. inxi
Inxi — это скрипт, который использует другие программы для создания хорошо структурированного легко читаемого отчета о различных аппаратных компонентах системы. Ознакомьтесь с полным руководством по inxi.
Вывод соответствующей информации о CPU/процессоре
Чтобы узнать больше о команде inxi и ее использовании, ознакомьтесь с этой статьей:
9. Hwinfo
Команда hwinfo — это программа для получения информации об оборудовании, которая может быть использована для сбора подробных сведений о различных аппаратных компонентах в системе Linux.
Она также отображает информацию о процессоре. Вот быстрый пример:
Если не использовать опцию «—short», команда отобразит гораздо больше информации о каждом ядре CPU, например, архитектуру и характеристики процессора.
Чтобы более подробно изучить команду hwinfo, ознакомьтесь с этой статьей:
Заключение
Это были некоторые команды для проверки информации о CPU в системах на базе Linux, таких как Ubuntu, Fedora, Debian, CentOS и др.
Примеры других команд для проверки информации о CPU смотрите в этой статье:
Большинство команд обрабатываются с помощью интерфейса командной строки и выводятся в текстовом формате. Для GUI интерфейса используйте программу Hardinfo.
Она показывает подробности об аппаратном обеспечении различных компонентов в простом для использования GUI интерфейсе.
Если вы знаете какую-либо другую полезную команду, которая может отображать информацию о CPU, сообщите нам об этом в комментариях ниже
Если вы хотели бы узнать подробнее о формате обучения и программе, познакомиться с преподавателем курса — приглашаем на день открытых дверей онлайн. Регистрация здесь.
А если вам интересно развитие в этой сфере с нуля до pro, рекомендуем ознакомиться с учебной программой специализации.
Источник
What specifically are wall-clock-time, user-cpu-time, and system-cpu-time in UNIX?
I can take a guess based on the names, but what specifically are wall-clock-time, user-cpu-time, and system-cpu-time in UNIX?
Is user-cpu time the amount of time spent executing user-code while kernel-cpu time the amount of time spent in the kernel due to the need of privileged operations (like IO to disk)?
What unit of time is this measurement in?
And is wall-clock time really the number of seconds the process has spent on the CPU or is the name just misleading?
4 Answers 4
Wall-clock time is the time that a clock on the wall (or a stopwatch in hand) would measure as having elapsed between the start of the process and ‘now’.
The user-cpu time and system-cpu time are pretty much as you said — the amount of time spent in user code and the amount of time spent in kernel code.
The units are seconds (and subseconds, which might be microseconds or nanoseconds).
The wall-clock time is not the number of seconds that the process has spent on the CPU; it is the elapsed time, including time spent waiting for its turn on the CPU (while other processes get to run).
Wall clock time: time elapsed according to the computer’s internal clock, which should match time in the outside world. This has nothing to do with CPU usage; it’s given for reference.
User CPU time and system time: exactly what you think. System calls, which include I/O calls such as read , write , etc. are executed by jumping into kernel code and executing that.
If wall clock time CPU time, you’re waiting for disk, network or other devices.
All are measured in seconds, per the SI.
real or wall-clock
real 7m2.444s
On a system with 24 core processor, this cmd/process took 7+ mins to complete. That by utilizing the most possible parallelism with all given cores.
user
user 76m14.607s
The cmd/process has utilized this much amount of cpu time. In other words, on machine with single core CPU, the real and user will be nearly equal, so the same command will take
76 mins to complete.
sys
sys 2m29.432s
This is the time taken by the kernel to execute all the basic/system level operations to run this cmd, including context switching, resource allocation, etc.
Note: The example assumes that your command utilizes parallelism/threads.
Источник