How to Check CPU Usage on Linux
Monitoring CPU usage is a critical task for anyone managing Linux systems, whether you’re a system administrator diagnosing performance issues or a regular user trying to understand why your computer is running slowly. Linux provides a rich set of tools that allow you to effectively monitor and analyze CPU utilization, helping you identify resource-intensive processes and optimize system performance.
In this comprehensive guide, we’ll explore various methods to check CPU usage on Linux, from basic command-line utilities to advanced monitoring techniques. You’ll learn how to interpret different CPU metrics, identify performance bottlenecks, and take appropriate actions to maintain optimal system performance.
Understanding CPU Metrics in Linux
Before diving into specific monitoring tools, it’s essential to understand what CPU metrics actually represent and how to interpret them correctly.
CPU utilization in Linux is typically broken down into several categories:
User time (us): Percentage of CPU time spent running user space processes. This represents applications and programs running on your system.
System time (sy): Percentage of CPU time spent on kernel operations, including system calls and hardware interruptions.
Nice time (ni): Percentage of CPU time spent on processes with modified scheduling priority (nice value).
Idle time (id): Percentage of time the CPU is not doing any work. Higher idle percentages indicate lower system load.
I/O wait (wa): Percentage of time the CPU is waiting for I/O operations to complete. High I/O wait times suggest potential disk bottlenecks.
Steal time (st): In virtualized environments, this represents the time waiting for the hypervisor to schedule the virtual CPU. High steal time indicates overcommitted resources on the host system.
Understanding these metrics is crucial for proper interpretation of CPU usage data. For example, a system with high I/O wait might need storage optimization rather than CPU upgrades.
What Constitutes Normal vs. High CPU Usage
Normal CPU usage varies depending on your system’s workload and hardware capabilities. For a typical desktop system:
- 0-20%: Light usage, system is mostly idle
- 20-70%: Normal operation under moderate workload
- 70-90%: Heavy workload, but still within acceptable limits
- 90-100%: System is under extreme load, potential performance issues
For servers, consistent usage above 70% might indicate the need for load balancing or hardware upgrades, especially if accompanied by degraded performance.
Load Averages Explained
Linux also provides load average metrics, which represent the average number of processes waiting for CPU time. These are typically displayed as three numbers indicating the 1-minute, 5-minute, and 15-minute averages.
For example, a load average of “2.15, 1.75, 1.20” means:
- 2.15 processes were waiting for CPU time, on average, over the last minute
- 1.75 processes over the last 5 minutes
- 1.20 processes over the last 15 minutes
On a single-core system, load averages above 1.0 indicate CPU saturation. For multi-core systems, the threshold is generally the number of CPU cores.
The top Command: Linux’s Standard CPU Monitor
The top
command is one of the most fundamental and widely available tools for monitoring CPU usage in Linux. It provides a dynamic, real-time view of system performance.
Basic Usage
To start monitoring with top, simply open a terminal and type:
top
This will display a continuously updating list of processes sorted by CPU usage by default. The header section shows system-wide statistics, including CPU, memory, and load average information.
Interpreting the Output
The top section of the display shows overall CPU statistics:
%Cpu(s): 10.0 us, 5.0 sy, 0.0 ni, 84.3 id, 0.7 wa, 0.0 hi, 0.0 si, 0.0 st
This breaks down as:
- 10.0% user processes
- 5.0% system processes
- 0.0% processes with altered nice values
- 84.3% idle time
- 0.7% waiting for I/O
- 0.0% hardware interrupts
- 0.0% software interrupts
- 0.0% stolen by the hypervisor
You can calculate overall CPU utilization with: CPU utilization = 100 – idle time.
Useful Keyboard Shortcuts
While top is running, you can use various keyboard shortcuts to customize the display and interact with processes:
- Press
1
to show individual CPU core statistics - Press
M
to sort processes by memory usage - Press
P
to sort processes by CPU usage (default) - Press
T
to sort processes by run time - Press
k
followed by a PID to kill a process - Press
r
to renice a process - Press
q
to quit top
For a less cluttered view that focuses on active processes, use:
top -i
This hides idle processes, making it easier to identify those consuming CPU resources.
The htop Command: An Enhanced Alternative
While top
provides essential CPU monitoring capabilities, htop
offers a more user-friendly and feature-rich alternative. It’s not installed by default on most Linux distributions but is available in standard repositories.
Installation
To install htop on Debian/Ubuntu-based distributions:
sudo apt install htop
For Red Hat/Fedora-based distributions:
sudo dnf install htop
Basic Usage and Features
Launch htop by typing:
htop
Compared to top, htop offers several advantages:
- Color-coded output for better readability
- Graphical CPU, memory, and swap usage bars
- Mouse support for easier navigation
- Built-in process management capabilities
- Vertical and horizontal process trees
- Customizable interface
Navigating and Customizing htop
htop’s interface is more intuitive than top’s. You can:
- Use arrow keys to navigate the process list
- Press F5 to view processes as a tree
- Press F6 to sort by different columns
- Press F9 to send signals to processes (including kill)
- Press F10 or q to quit
The header section displays CPU usage for each core individually, along with memory and swap usage bars. This makes it much easier to spot imbalances across CPU cores or identify memory pressure.
The mpstat Command: Detailed CPU Statistics
For more detailed CPU statistics, particularly on multi-core systems, the mpstat
command is invaluable. It’s part of the sysstat package, which may need to be installed separately.
Installation
On Debian/Ubuntu systems:
sudo apt install sysstat
On Red Hat/Fedora systems:
sudo dnf install sysstat
Basic Usage
The simplest way to use mpstat is:
mpstat
This displays average statistics since the system boot. For real-time monitoring, specify an interval and count:
mpstat 2 5
This will show CPU statistics every 2 seconds for 5 iterations.
Monitoring Individual CPU Cores
One of mpstat’s key strengths is its ability to show statistics for each CPU core, which is particularly useful for identifying imbalances in workload distribution:
mpstat -P ALL
This command displays statistics for each processor separately, allowing you to identify if certain cores are overloaded while others remain idle.
Interpreting mpstat Output
The output includes several columns:
%usr
: Percentage of CPU time spent in user space%sys
: Percentage of CPU time spent in kernel space%iowait
: Percentage of time CPU was waiting for I/O operations%idle
: Percentage of time CPU was idle%intr
: Percentage of time spent servicing interrupts
High %iowait
values indicate I/O bottlenecks, while high %usr
suggests CPU-intensive user applications.
The iostat Command: I/O and CPU Monitoring
The iostat
command provides insights into both CPU utilization and disk I/O performance, making it particularly useful for understanding the relationship between disk activity and CPU usage.
Installation
iostat is part of the sysstat package:
sudo apt install sysstat # Debian/Ubuntu
sudo dnf install sysstat # Red Hat/Fedora
Basic Usage
To display basic CPU and device statistics:
iostat
For continuous monitoring with a 2-second interval:
iostat 2
Focusing on CPU Statistics
To display only CPU statistics:
iostat -c
The output includes:
%user
: Percentage of CPU time spent in user space%nice
: Percentage of CPU time spent on niced processes%system
: Percentage of CPU time spent in kernel space%iowait
: Percentage of CPU time waiting for I/O%steal
: Percentage of time in involuntary wait%idle
: Percentage of CPU time spent idle
Like with other tools, you can calculate the overall CPU utilization using the formula: CPU utilization = 100 – %idle.
The vmstat Command: Virtual Memory and CPU Statistics
The vmstat
command (virtual memory statistics) provides insights into system memory, CPU activity, I/O, and system processes. It’s particularly useful for identifying memory-related performance issues that might impact CPU usage.
Basic Usage
For a one-time snapshot of system statistics:
vmstat
For continuous monitoring with a specified interval (in seconds):
vmstat 2
Understanding the Output
The vmstat output is divided into several sections:
- Procs: Process information (r: runnable, b: blocked)
- Memory: Memory utilization (swpd: virtual memory used, free: idle memory)
- Swap: Swap space activity (si: memory swapped in, so: memory swapped out)
- IO: I/O operations (bi: blocks received from devices, bo: blocks sent to devices)
- System: System operations (in: interrupts per second, cs: context switches)
- CPU: Breakdown of CPU usage (us: user time, sy: system time, id: idle time, wa: I/O wait)
High values in the “r” column (runnable processes) might indicate CPU contention, while high values in the “b” column (blocked processes) could suggest I/O bottlenecks.
The ps Command: Process-Specific CPU Monitoring
While the previous commands provide system-wide CPU statistics, the ps
command allows you to examine resource usage at the process level, helping you identify specific applications consuming excessive CPU resources.
Basic Usage for CPU Monitoring
To view all processes with CPU usage information:
ps aux
To sort processes by CPU usage (highest first):
ps aux --sort=-%cpu
To display the top 10 CPU-consuming processes:
ps aux --sort=-%cpu | head -11
Alternatively, you can use:
ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10
This displays the CPU percentage, process ID, user, and command for the top 10 CPU-intensive processes.
Custom Output Formats
You can customize the ps output to focus on specific metrics:
ps -eo pid,ppid,cmd,%cpu,%mem --sort=-%cpu
This displays the process ID, parent process ID, command, CPU usage percentage, and memory usage percentage, sorted by CPU usage.
The sar Command: Historical CPU Performance
The System Activity Reporter (sar) is a powerful tool for analyzing historical CPU performance. It can both collect and report system activity information, making it invaluable for tracking performance trends over time.
Installation
sar is part of the sysstat package:
sudo apt install sysstat # Debian/Ubuntu
sudo dnf install sysstat # Red Hat/Fedora
Enabling Data Collection
On many systems, you’ll need to enable sar data collection:
sudo systemctl enable sysstat
sudo systemctl start sysstat
Viewing Current CPU Statistics
To view real-time CPU statistics:
sar -u 2 5
This displays CPU usage every 2 seconds for 5 iterations.
Accessing Historical Data
To view CPU statistics from earlier today:
sar -u
To view data from a specific day:
sar -u -f /var/log/sysstat/sa20 # Replace 20 with the day of the month
The output includes detailed CPU statistics similar to those provided by other tools, but with the added benefit of historical perspective.
Additional CPU Monitoring Tools
Beyond the standard command-line utilities, several other tools provide valuable CPU monitoring capabilities:
nmon (Nigel’s Monitor)
A versatile system monitor that displays performance information about the CPU, memory, network, disks, and more:
sudo apt install nmon # Install on Debian/Ubuntu
nmon # Run the tool
Use the ‘c’ key to focus on CPU statistics.
glances
A modern, cross-platform system monitoring tool with a web interface option:
sudo apt install glances # Install on Debian/Ubuntu
glances # Run the tool
uptime
A simple command to quickly check system load averages:
uptime
The output shows the current time, system uptime, number of users, and load averages for the past 1, 5, and 15 minutes.
Finding Top CPU Consumers
When troubleshooting high CPU usage, identifying the most resource-intensive processes is crucial. Here are some effective commands:
Using top for Real-time Monitoring
top -o %CPU
This starts top with processes sorted by CPU usage.
Using ps for a Quick Snapshot
ps aux --sort=-%cpu | head -11
This shows the top 10 CPU-consuming processes (plus the header).
Continuous Monitoring with watch
watch "ps aux --sort=-%cpu | head -11"
This updates the list of top CPU consumers every 2 seconds.
Finding Process-Specific Information
To get detailed information about a specific process:
ps -p <PID> -o %cpu,%mem,cmd
Replace <PID>
with the actual process ID.
Advanced CPU Monitoring Techniques
For more sophisticated CPU monitoring needs, consider these advanced techniques:
Continuous Monitoring with the watch Command
The watch command allows you to run any command periodically:
watch -n 1 "mpstat -P ALL"
This runs mpstat every second, showing statistics for all CPU cores.
Logging CPU Statistics to Files
To log CPU statistics for later analysis:
sar -u 5 288 > cpu_stats.log
This collects CPU data every 5 seconds for 24 hours (288 * 5 minutes = 24 hours).
Creating Custom Monitoring Scripts
A simple bash script to monitor CPU usage:
#!/bin/bash
while true; do
echo "$(date): $(top -bn1 | grep "Cpu(s)" | awk '{print $2+$4}')% CPU"
sleep 5
done
Save this as cpu_monitor.sh
, make it executable with chmod +x cpu_monitor.sh
, and run it with ./cpu_monitor.sh
.
CPU Monitoring in Virtual Environments
Virtualized environments present unique challenges for CPU monitoring due to the abstraction layer between virtual and physical resources:
Understanding CPU Steal Time
In virtualized environments, CPU steal time (%st
) represents the percentage of time the virtual CPU was ready to run but the hypervisor was servicing another virtual processor. High steal time indicates resource contention at the hypervisor level.
To monitor steal time:
top
Look for the st
value in the CPU statistics line.
Cloud-Specific Considerations
In cloud environments, you might not have visibility into the physical hardware. Focus on:
- Monitoring steal time to detect resource contention
- Using cloud provider metrics alongside traditional Linux tools
- Understanding the resource allocation model of your cloud provider
For AWS instances, the CloudWatch agent can collect and report CPU metrics, complementing traditional Linux monitoring tools.
Troubleshooting High CPU Usage
When faced with high CPU usage, follow these steps to diagnose and resolve the issue:
Identify Resource-Intensive Processes
First, identify which processes are consuming the most CPU:
top -o %CPU
or
ps aux --sort=-%cpu | head -11
Analyze Process Behavior
Once you’ve identified high-CPU processes, determine if they’re:
- Legitimate high usage: Some tasks (like video encoding) naturally use high CPU
- Runaway processes: Processes stuck in loops or experiencing errors
- Malware or unauthorized processes: Unexpected processes consuming resources
Common Causes and Solutions
For high CPU usage, consider these common causes and solutions:
- Too many browser tabs: Close unnecessary tabs or restart the browser
- Background services: Disable unnecessary services using
systemctl
- Software bugs: Update to the latest version or check for known issues
- Insufficient resources: Consider upgrading hardware if consistently at capacity
- Malware: Run security scans with tools like ClamAV
When to Take Action
As a general guideline:
- Short CPU spikes (< 5 minutes): Normal for many workloads, typically no action needed
- Sustained high usage (> 15 minutes): Investigate if not expected
- System becomes unresponsive: Immediate investigation required
CPU Monitoring Best Practices
To effectively monitor CPU usage on Linux systems, follow these best practices:
Establish Baseline Performance
Before troubleshooting, establish what “normal” looks like for your system:
sar -u 10 60 > baseline_cpu.log
This collects CPU data every 10 seconds for 10 minutes, providing a baseline for comparison.
Set Up Regular Monitoring
Use cron to schedule regular monitoring:
# Add to crontab (crontab -e)
*/10 * * * * /usr/bin/sar -o /var/log/sar/cpu_`date +\%H\%M` -u 1 2 >/dev/null 2>&1
This runs sar every 10 minutes and saves the output to a file.
Configure Alerts for Abnormal Usage
Tools like Nagios or Zabbix can send alerts when CPU usage exceeds thresholds:
# Example Nagios check_command for CPU usage
define command {
command_name check_cpu
command_line $USER1$/check_nrpe -H $HOSTADDRESS$ -c check_cpu -a warn=$ARG1$ crit=$ARG2$
}
Balance Monitoring Overhead
Monitoring itself consumes resources. Balance comprehensive monitoring with minimal overhead:
- Use lightweight tools for continuous monitoring (e.g., sar)
- Schedule more intensive tools during off-peak hours
- Adjust collection intervals based on system importance and load