- 14 Command Line Tools to Check CPU Usage in Linux
- 1) Top
- 2) Iostat
- 3) Vmstat
- 4) Mpstat
- 5) Sar
- 6) CoreFreq
- 7) Htop
- 8) Nmon
- 9) Glances
- 10) Cpustat
- 11) perf
- 12) tiptop
- 13) ps command
- 14) dstat command
- Conclusion
- 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
14 Command Line Tools to Check CPU Usage in Linux
CPU performance is one aspect of measuring the performance of a system. Monitoring the performance of CPU is essential to debug processes inside any system, manage system resources, making system decisions, and evaluating and examining systems in real-time.
There are a lot of tools available to monitor and display CPU performance. Operating systems have built-in system calls which these tools rely on to extract the performance readings.
In this tutorial, we will explore the best CPU usage monitoring tool and their usages in any Linux based distros.
1) Top
The top command displays real-time view of performance-related data of all running processes in a system. By default, the top command updates data every 5 seconds. Type ‘top’ from the terminal to view the statistical data related to the performance of a system.
To modify the output of top command, press:
‘P’ to sort by CPU usage.
‘I’ to remove the idle processes from the display and to revert back press ‘I’ again.
‘M’ to sort the data by memory usage.
‘S’ to sort by how long the processes have been running type.
‘P’ to sort by CPU usage.
‘U’ to view processes owned by a specific user.
‘K’ to kill processes.
‘R’ to renice processes.
2) Iostat
The iostat command list CPU utilization, device utilization and network file system utilization. This utility display system’s average CPU utilization since the last reboot. Running the following command without any options displays all the three reports.
To list the individual report use -c, -d and -h switch for CPU utilization, device utilization and network file system utilization. The following command will break the CPU utilization into user processes, system processes, I/O wait and idle time.
The following command will display extended statistics (-x), the number of times (-t) each report should be displayed for CPU utilization (-c).
3) Vmstat
The vmstat command will display statistics about system processes, memory, swap, I/O, and the CPU performance. For displaying statistics, the data is collected from the last time the command was run to the present. In case the command never being run, the data will be from the last reboot to the current time.
On multiple CPU systems, vmstat averages the number of CPUs into the output. The vmstat command updates its output like top command.
The following command will update its report every 5 seconds until there is an interrupt.
The following command will display the data that will update in every 5 seconds and the values will be re-measured and reported every 1 second.
The first line prints the average values since the last time the computer was rebooted. The rest of the lines will display their respective current values. A normal user can run vmstat command.
4) Mpstat
Mpstat is part of the sysstat package in Linux. The mpstat command writes to standard output about activities for each available processor, processor 0 being the first one. If no activity has been selected, then the default report is the CPU utilization report.
mpstat without any option will display Global Average Activities of all CPUs
mpstat with -p option and ‘ALL’ will list statistics about all CPUs one by one starting from 0.
The following command will list average CPU usage for 4 times, each after 2 seconds.
5) Sar
The sar is a performance monitoring tool for collecting, viewing and recording performance data and can list what a system is doing all the time. Sar command can generate report and email them to system admin. The statistics reported by sar include I/O transfer rates, paging activity, process-related activities, interrupts, network activity, memory and swap space utilization, CPU utilization, kernel activities and TTY statistics, among others. Run sar without any option and check the output. The default output list statistics for every 10 minutes and a final average.
Display CPU statistics 3 times with 2 second interval.
The following command displays cumulative real-time CPU usage of all CPU for every 2 seconds a total of 3 times.
The ‘-P ALL’ option displays statistics for ALL the individual Cores. If your system has 4 cores then the ‘CPU column’ will contain the number 0, 1, 2, 3 indicating the corresponding CPU core numbers. The ‘2 3’ option displays the statistics every 2 seconds for 3 times.
The ‘-P 2’ option displays statistics for third core every 2 seconds for 3 times.
6) CoreFreq
CoreFreq is a CPU performance monitoring software designed for 64-bits Processors w/ architectures Intel Atom, Core2, Nehalem, SandyBridge and superior, AMD Family. The CoreFreq provides a framework for retrieving CPU data with a high degree of precision. The kernel module, daemon, and userland command-line interface (CLI) are the three parts of Corefreq. The kernel module will have full access to the host. It is its responsibility to gather the low-level data. The userland daemon collects the data. You should be root user to run the daemon. Finally, CoreFreq comes with a terminal interface to report data in a nice human-readable format. That CLI tool is an ordinary process and may be used by the end user.
Prerequisite
i) CoreFreq uses the low-level counter and hence you should first disable NMI watchdog through /etc/default/grub. Edit /etc/default/grub and add the ‘nmi_watchdog=0’ kernel command line argument and subsequently run update-grub.
ii) No Virtualization. VMs don’t provide access to the registers that the CoreFreq driver employs.
Install CoreFreq
Install the kernel module with insmod
List the CoreFreq module with lsmod
The output of dmesg command shows CoreFreq has been recognized by the processor.
Start the CoreFreq daemon
Now start the corefreq client as a user.
7) Htop
Htop is a process viewer and a text-mode application for system monitoring in real-time like top. It displays a complete list of the processes that are running and is easy to use. It is based on ncurses for viewing the processes in a GUI-like environment running in the terminal. Htop displays usage per CPU along with memory and swap usage with a significant text graph printed at the top. Htop is very much convenient to use and easy to understand. Once you start using HTOP, you might not return to TOP.
Install htop using the following command in the terminal
Run htop using the following command.
8) Nmon
nmon (Nigel’s performance Monitor for Linux & AIX) has been developed by IBM employee Nigel Griffiths. This tool is used to monitor system resources such as CPU, memory, network, disks, file systems, NFS, top processes in the terminal. NMON supports various architectures like POWER, x86, x86_64, Mainframe and ARM (Raspberry Pi). This tool helps system administrator to tune, benchmark performance information to troubleshoot the CPU/system performance when there is some issues. For real-time monitoring, it uses curses library for low CPU impact and displays statistics on the screen and update in every two seconds. nmon consumes less CPU memory as compared with other tools since it uses curses library.
Installation
CentOS users need to install/enable EPEL Repository in order to install nmon.
Type nmon in the terminal and press enter, nmon will display a welcome screen with all the options to use it further. If you want to display CPU utilization, press c and to hide the CPU utilization widgets statistics, press ‘c’ again.
9) Glances
Glances is a cross-platform curses-based monitoring tool written in Python that uses the psutil library to fetch data from the system. Glance monitor CPU, Load Average, Memory, Network Interfaces, Disk I/O, Processes and File System spaces utilization.
Install glances in your system with the following command.
In Ubuntu:
In Centos:
You can run Glances in 3 modes-
1. Standalone
If you want to monitor your local machine(Standalone), simply run-
2. Client/Server
If you want to remotely monitor a machine then execute the following on the server.
and then from the client, execute the following command.
where @server is the IP address or hostname of the server.
3. Webserver
Run the glances in web server mode by executing the following command in the terminal.
To change the refresh rate of the page, just add the period in seconds at the end of the URL. For example, to refresh the page every 30 seconds, append 10 to the glances server URL from the browser.
10) Cpustat
Cpustat is like a fancy sort of top that does different things. Most performance tools average CPU usage over a few seconds or even a minute. This results in a fantasy of excess capacity because of an abrupt increase in resource usage that is blended in with less busy periods. On the other hand, cpustat takes higher frequency samples of each process and summarizes these samples at a lower frequency. For example, it can measure a process in every 200ms and summarize the samples in every 5 seconds, including min/average/max values for some metrics.
Install Cpustat
Cpustat is written in Go language. Therefore, you need GO in your system. If it is not there then install it using following commands in the terminal.
In Ubuntu
In CentOS
Once Golang is installed in your system then create a directory for Cpustat and make this directory available to the GOPATH.
Install Cpustat and verify that the directories are copied over to the folder cpustat.
Add bin folder to the PATH environment variable. You can also add the following line to
/.bashrc or /etc/profile depending on what you are using.
There are two ways of displaying this data. Either a pure text list of the summary interval or a colorful scrolling dashboard of each sample. To display data in fancy terminal mode, execute the following command in the terminal.
To run in pure text mode, use the following command. In text mode, few system-wide summary metrics come from /proc/stat.
The following command will take a sample of all processes in every 500ms and summarize this data after 10 samples, which is every 5 seconds.
Use the following command to measure processes that are owned by either user root or user ubuntu. The overall system stats will still be measured.
Only measure processes of «apache» or «mysql». The -p option of cpustat takes a list of process ids returned by pgrep. pgrep is used to get the process ids ( -d option ).
Use the following command to write memory profile in a file.
11) perf
Perf can measure CPU performance counters, tracepoints, kprobes, and uprobes that is included in the Linux kernel, under tools/perf. perf began as a tool for using the performance counters subsystem in Linux, and has had various enhancements to add tracing capabilities. The perf tools are integrated into the Linux kernel since the 2.6 version and are based on the perf events subsystem. The perf profiler uses hardware counters to profile the application. The result of this profiler is explicit and fast. The perf utility can be found in the linux-tools package.
If you are interested in finding CPU performance for a particular ‘command’ like cp. The following perf command will profile cp while it is copying the entire directory Documents to new location (Docs).
If you want to find CPU counter statistics for a specified PID then use the following command until CTRL+C is pressed.
Find the basic CPU statistics, system wide, for 10 seconds using the following perf command. You can also omit any one of the options under -e option to be more specific.
Collect Sample on-CPU user instructions, for 5 seconds and then use perf report to view the report.
Collect sample CPU stack traces, once every 10,000 Level 1 data cache misses, for 5 seconds and then use perf report to view the report.
12) tiptop
Tiptop reads hardware performance counters and displays statistics about running Linux processes, such as IPC, or cache misses. It provides a dynamic real-time view of the tasks running in the system. Tiptop is very similar to top, but the information displayed comes from hardware counters.
It has two running modes, live-mode and batch-mode. In both modes, the system is periodically queried for the values of hardware counters, and various ratios are printed for each task.
13) ps command
We can use ps command to find cpu usage for each process or users. Given few examples to understand
To display the highest CPU & Memory utilization by processes run by root.
Run the following command to display CPU usage for the specific command:
To show processes for all users and not attached to a terminal in full format listing with a sort
14) dstat command
dstat command is a versatile tool for generating system resource statistics and it would also show cpu stats. You need to install it in order to use it
On Centos
On Ubuntu
To monitor program that is using the most CPU and consuming the most amount of memory.
Conclusion
In this tutorial, we have explored few CPU performance monitoring tool along with their usages. Be sure to read man pages for each of them, as it also documents the usages in detail. Remember that using these tools also takes a CPU slice. For example, top takes 3%-4% of CPU while glances take 15% to 20% of CPU. So while using any one of these, you need to consider this aspect as well. In a nutshell, you will be able to find which process is taking more CPU time, is there enough free memory, whether processes are stalled while waiting for I/O viz. disk or network access to complete read/write and much more by using a combination of few of them.
Источник
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:
Источник