Monitoring Linux Cpu Usage: A Comprehensive Guide

how to monitor cpu usage in linux

Monitoring CPU usage is an essential task for system administrators to ensure the efficient performance of their Linux systems. By understanding CPU usage, administrators can identify performance bottlenecks, detect resource-intensive processes, and optimise system performance. Linux offers a variety of powerful tools and commands to monitor CPU usage, including command-line tools and graphical utilities.

One of the most commonly used command-line tools is the top command, which provides real-time information about system resource usage, including CPU load and memory usage. The mpstat command is another popular choice, which is part of the sysstat package and provides detailed CPU performance statistics. Other useful commands include vmstat, sar, and iostat.

For those seeking a graphical representation of CPU performance, Linux offers graphical utilities such as GNOME System Monitor, KDE System Monitor, Conky, and Xfce Task Manager. These tools provide an intuitive visual display of CPU usage through graphs or percentage breakdowns of individual cores.

By leveraging these command-line tools and graphical utilities, system administrators can effectively monitor and optimise CPU usage in Linux systems, ensuring efficient performance and resource allocation.

Characteristics Values
Command to check CPU usage top
Command to display CPU activity mpstat
Command to show CPU utilization sar
Command to check average CPU usage iostat
Command to display system processes, memory, swap, I/O, and CPU performance vmstat
Command to check number of processing units available nproc
Command to dump the computer's Desktop Management Interface (DMI) or System Management BIOS table dmidecode
Command to list information about the Linux system inxi
Command to check if a CPU supports virtualization lscpu
Command to get detailed, in-depth information on the CPU class lshw
Command to get detailed information about the CPU cat /proc/cpuinfo
Command to check CPU usage htop
Command to view process-level CPU statistics ps

shundigital

Using the top command

The `top` command is a built-in utility in Linux that provides a real-time, dynamic view of system performance. It is one of the most commonly used commands for monitoring CPU utilisation.

To launch the `top` command, open a terminal window and type `top`. This will display a continuously updating screen showing various system metrics. By default, processes are sorted by CPU usage in descending order, with the most resource-intensive processes listed at the top. The initial line, often referred to as the header or summary line, displays information such as system time, uptime, number of users, and load average.

The `top` command provides a dynamic real-time view of the running system, including a summary of system information and a list of processes or threads managed by the Linux Kernel. The upper half of the screen contains statistics on processes and resource usage, while the lower half contains a list of currently running processes.

The `top` command also offers a range of interactive features. For example, pressing `k` allows you to send a signal (e.g. terminate or kill) to a selected process. Pressing `1` (numeric) shows individual CPU core utilisation if your system has multiple cores. Pressing `f` allows you to choose which columns to display and customise the output.

  • PID: Task's unique process ID
  • PR: Process's priority. Lower numbers indicate higher priority.
  • VIRT: Total virtual memory used by the task.
  • USER: User name of the task owner.
  • %CPU: Represents the CPU usage.
  • TIME+: CPU Time, reflecting more granularity through hundredths of a second.
  • SHR: Represents the shared memory size (kb) used by a task.
  • NI: Represents the Nice Value of the task. A negative value implies higher priority, and a positive value means lower priority.
  • %MEM: Shows the memory usage of the task.
  • RES: Amount of physical RAM the process is using, measured in kilobytes.
  • COMMAND: The name of the command that started the process.

shundigital

Using the htop command

The htop command in Linux is a command-line utility that offers an interactive and user-friendly way to monitor system resources and processes in real time. It is an improved version of the 'top' command, providing a full list of all running processes, along with details such as CPU, memory, and swap usage.

To use the htop command, follow these steps:

  • Open a terminal on your Linux system.
  • Install htop if it's not already installed. You can typically use package managers like apt or yum. For example, on Ubuntu or Debian-based systems, use the following command:

```

Sudo apt-get install htop

```

  • Once installed, simply run the command: htop
  • The htop interface will open, displaying real-time information about system resources. By default, the CPU utilization is shown in the header section.
  • The CPU usage is represented graphically, with a bar for each CPU core. The length of the bar indicates the utilization percentage of the respective core.
  • You can view detailed CPU usage for each process, listed in a table below the CPU utilization graph. The "%CPU" column shows the percentage of CPU usage for each process.
  • Use the arrow keys to navigate through the processes, and the F keys to access additional options and filters. For example, pressing F5 will sort the processes based on different criteria like CPU or memory usage.
  • To exit htop, press "q".

Htop Command Options:

The htop command offers various options to customize your experience:

  • -d, --delay=DELAY: This option sets the delay between updates in tenths of seconds. For example, a delay of 10 tenths of a second equals one second.
  • -C, --no-color: This option starts htop in monochrome mode, disabling color coding.
  • -u, --user=USERNAME: This option displays only the processes owned by a specific user.
  • Interactive Commands:
  • Arrows, Page Up, Page Down, Home, End: Scroll through the process list.
  • Space: Tag or untag a process.
  • U: Untag all processes.
  • F4: Filter processes by name.
  • F5: Display processes in a tree view.
  • F7: Increase the selected process's priority (superuser only).
  • F8: Decrease the selected process's priority.
  • F9: Kill a process.

The htop command is a powerful and flexible tool for system administrators and users who want detailed insights into their system's performance and resource utilization.

shundigital

Using the mpstat command

The mpstat command is part of a software bundle called sysstat. Most RHEL-based distributions include this software package. For Debian and Ubuntu systems, you can install the sysstat package using the following command:

`sudo apt install sysstat`

Once the process is complete, enter the mpstat command:

`mpstat`

The system will then display the usage for each processor (or processor core). The first line is a set of column labels, and the second line is the value for each column:

  • %usr: % CPU usage at the user level.
  • %nice: % CPU usage for user processes labelled "nice".
  • %sys: % CPU usage at the system (Linux kernel) level.
  • %iowait: % CPU usage idling, waiting on a disk read/write.
  • %irq: % CPU usage handling hardware interrupts.
  • %soft: % CPU usage handling software interrupts.
  • %steal: % CPU usage being forced to wait for a hypervisor handling other virtual processors.
  • %guest: % CPU usage spent running a virtual processor.
  • %idle: % CPU usage on idle time (no processes and not waiting on a disk read/write).

You can also specify a single processor to report on by using the "-P" switch:

`mpstat -P 0`

This will display a report for the first processor (CPU 0).

To show total statistics and list processes by individual CPU, use the following command:

`mpstat -P ALL`

The mpstat command only takes a snapshot of CPU usage. To take a series of snapshots, you can specify an interval and the number of reports:

`mpstat 5 7`

This command will generate 7 snapshots, each 5 seconds apart, and calculate average values.

You can also use mpstat to display the utilisation of each CPU individually. If you are using an SMP (Multiple CPU) system, use the following command:

`mpstat`

This will report processor-related statistics.

shundigital

Using the iostat command

The iostat command is used for monitoring system input/output statistics for devices and partitions. It observes the time the devices are active in relation to their average transfer rates. The iostat report can be used to change the system configuration to balance the input/output between the physical disks.

The iostat command is part of the sysstat package, which may already be installed on your Linux distribution. If not, you can install it using the package manager for your distribution. For example, on Debian/Ubuntu-based systems, you can use the command:

`sudo apt-get install sysstat`

For RHEL/CentOS/Fedora-based systems, you can use:

`sudo yum install sysstat`

The basic syntax of the iostat command is as follows:

`iostat [options] [devices] [interval] [count]`

  • Options: Flags that modify the command behaviour or specify the type of information to display.
  • Devices: The devices for which you want to display I/O statistics. By default, iostat shows statistics for all devices.
  • Interval: The time interval (in seconds) between updates. By default, iostat displays a single report.
  • Count: The number of updates to display before exiting. By default, iostat runs indefinitely if an interval is specified.

To display basic CPU and disk I/O statistics, simply run the command without any options:

`iostat`

The output of the iostat command consists of two sections: CPU statistics and device statistics.

CPU Statistics:

  • %user: The percentage of time the CPU spent executing user-level processes.
  • %nice: The percentage of time the CPU spent executing user-level processes with a positive nice value.
  • %system: The percentage of time the CPU spent executing system-level processes.
  • %iowait: The percentage of time the CPU spent waiting for I/O operations to complete.
  • %steal: The percentage of time the CPU spent in involuntary wait while the hypervisor serviced another virtual processor.
  • %idle: The percentage of time the CPU was idle.

Device Statistics:

  • Device: The name of the device (e.g., sda, sdb).
  • Tps: The number of transfers per second (I/O requests) sent to the device. Higher tps indicates a busier processor.
  • KB_read/s: The number of kilobytes read from the device per second.
  • KB_wrtn/s: The number of kilobytes written to the device per second.
  • KB_read: The total number of kilobytes read from the device.
  • KB_wrtn: The total number of kilobytes written to the device.

You can also use various options with the iostat command to customise the output:

  • `-c`: Display only the CPU statistic.
  • `-d`: Display only the device report.
  • `-x`: Show extended I/O statistics for devices.
  • `-k`: Capture statistics in kilobytes or megabytes.
  • `-m`: Create a report with megabytes unit.
  • `-p [device]`: Display statistics for a specific partition or disk.
  • `--human`: Show output in a human-readable format.

For example, to display extended device statistics in a human-readable format updated every 2 seconds indefinitely, use:

`iostat -xdm --human 2`

shundigital

Using the vmstat command

The vmstat command (short for virtual memory statistics) is a built-in monitoring utility in Linux that provides detailed information about system memory, CPU usage, and other vital statistics. The command helps identify performance bottlenecks and diagnose system problems.

To use the vmstat command, you need a machine running Linux and an account with sudo/root privileges. The basic syntax for the vmstat command is:

Vmstat [options][delay [count]]

  • Options: Various switches to customize the output.
  • Delay: Defines the time elapsed between output updates.
  • Count: The number of output updates after the specified delay interval. If count isn't set, the default value is infinite.

Here's an example of the basic output of the vmstat command:

Procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----

R b swpd free buff cache si so bi bo in cs us sy id wa st

In this output, you can find information about processes, memory, swap, IO, system, and CPU. Here's a breakdown of the CPU-related fields:

  • Us: The percentage of CPU time spent on non-kernel processes.
  • Sy: The percentage of CPU time spent on kernel processes.
  • Id: The percentage of idle CPU.
  • Wa: The percentage of CPU time spent waiting for Input/Output.
  • St: The percentage of CPU time stolen by a virtual machine.

To monitor CPU usage using vmstat, follow these steps:

  • Open a terminal or SSH into your Linux system.
  • Run the vmstat command with the -a option to display active and inactive memory information:

Vmstat -a

  • Observe the output and look for the "CPU" section. Monitor the "us," "sy," and "id" columns to gauge CPU utilization. Higher values in the "us" and "sy" columns indicate increased CPU usage, while a higher value in the "id" column suggests more idle CPU time.
  • You can also use the -d option to get detailed statistics on disk usage:

Vmstat -d

  • This will provide read/write stats for each disk, helping you identify any disk-related performance issues.
  • Additionally, you can use the -s option to get detailed information about memory, event counters, and CPU scheduling statistics:

Vmstat -s

  • This will give you insights into memory usage, CPU ticks for different types of processes, and various event counters.
  • To get real-time updates, specify a sampling period using the delay option. For example, to get updates every 2 seconds, use:

Vmstat 2

Press Ctrl+C to stop the command and exit.

Frequently asked questions

Written by
Reviewed by
Share this post
Print
Did this article help you?

Leave a comment