How to Check CPU Usage on Linux
Monitoring CPU usage on Linux systems is crucial for maintaining optimal performance and identifying potential bottlenecks. Whether you’re a system administrator, developer, or power user, understanding how to check and analyze CPU utilization can help you keep your Linux machines running smoothly. This comprehensive guide will walk you through various methods to monitor CPU usage, from command-line tools to graphical interfaces, and provide you with the knowledge to troubleshoot high CPU consumption effectively.
1. Introduction to CPU Monitoring in Linux
CPU (Central Processing Unit) is the brain of your computer, responsible for executing instructions and performing calculations. Monitoring its usage is essential for several reasons:
- Identifying performance issues and bottlenecks
- Optimizing resource allocation
- Detecting malicious activities or runaway processes
- Capacity planning and hardware upgrades
Linux provides a wealth of tools and utilities for CPU monitoring, each offering unique insights into system performance. Key metrics to watch include:
- User time: CPU time spent on user processes
- System time: CPU time spent on kernel operations
- Idle time: Percentage of time the CPU is not actively processing
- I/O Wait: Time spent waiting for I/O operations to complete
Let’s dive into the various methods to check CPU usage on Linux systems.
2. Terminal-Based Monitoring Tools
Command-line tools are the backbone of Linux system monitoring. They’re lightweight, versatile, and can be easily scripted for automated monitoring.
2.1. Using Top Command
The ‘top
‘ command is a built-in, real-time system monitor that provides a dynamic view of system processes.
To use top, simply open a terminal and type:
top
Key information provided by top includes:
- Load averages for the last 1, 5, and 15 minutes
- CPU usage breakdown (%us, %sy, %id, %wa)
- Process list sorted by CPU usage
Useful top commands:
- Press ‘Shift+P’ to sort processes by CPU usage
- Press ‘k’ to kill a process (enter PID when prompted)
- Use ‘top -d 5’ to set a custom refresh interval (e.g., 5 seconds)
2.2. Advanced Monitoring with htop
htop is an enhanced version of top with a more user-friendly interface and additional features.
To install htop on Debian/Ubuntu systems:
sudo apt install htop
For RHEL/CentOS systems:
sudo dnf install htop
Launch htop by typing:
htop
htop offers:
- Color-coded output for easy reading
- Per-core CPU usage graphs
- Process tree view (press F5)
- Ability to scroll horizontally and vertically
2.3. mpstat for Multi-Core Analysis
mpstat is part of the sysstat package and provides detailed CPU statistics for multi-core systems.
Install sysstat:
sudo apt install sysstat # Debian/Ubuntu
sudo dnf install sysstat # RHEL/CentOS
To view CPU usage for all cores:
mpstat -P ALL
For continuous monitoring:
mpstat 2 5 # Report every 2 seconds, 5 times
mpstat helps identify imbalances between cores, which can indicate threading issues in applications.
2.4. vmstat for System-Wide Insights
vmstat provides a snapshot of system statistics, including CPU, memory, and I/O.
vmstat 1 5 # Report every 1 second, 5 times
Key CPU-related columns in vmstat output:
- ‘r’: Number of runnable processes (running or waiting for CPU)
- ‘us’: User CPU time
- ‘sy’: System CPU time
- ‘id’: Idle CPU time
A high ‘r’ value combined with low ‘id’ (idle) percentage often indicates CPU saturation.
2.5. iostat for I/O Correlation
iostat shows CPU statistics and input/output statistics for devices and partitions.
iostat -c 2 3 # Report CPU stats every 2 seconds, 3 times
Pay attention to the ‘%iowait’ column, as high values can indicate I/O bottlenecks affecting CPU performance.
2.6. Process-Specific Analysis with ps
The ps command provides a snapshot of current processes. To sort processes by CPU usage:
ps -eo pid,ppid,%cpu,%mem,cmd --sort=-%cpu | head
For continuous monitoring of top CPU consumers:
watch -n 2 "ps -eo pid,%cpu --sort=-%cpu | head -n 10"
2.7. Nmon for Enterprise Monitoring
Nmon (Nigel’s Monitor) is a multi-purpose system monitoring tool popular in enterprise environments.
To install nmon:
sudo apt install nmon # Debian/Ubuntu
sudo dnf install nmon # RHEL/CentOS
Launch nmon in interactive mode:
nmon
For long-term data collection:
nmon -f -s 300 -c 288 # Collect data every 5 minutes for 24 hours
3. Graphical Monitoring Solutions
While command-line tools offer power and flexibility, graphical tools can provide a more intuitive interface for CPU monitoring.
3.1. GNOME System Monitor
GNOME System Monitor is the default system monitor for GNOME-based desktops.
Launch it from the application menu or by typing:
gnome-system-monitor
The ‘Resources’ tab provides a real-time graph of CPU usage, along with memory and network statistics.
3.2. KDE KSysGuard
KSysGuard is KDE’s system monitor application, offering customizable sensor displays and remote monitoring capabilities.
To launch KSysGuard:
ksysguard
KSysGuard allows you to create custom dashboards with various system sensors, including detailed CPU metrics.
3.3. Conky Custom Dashboards
Conky is a highly customizable system monitor that can display CPU usage directly on your desktop.
Install Conky:
sudo apt install conky # Debian/Ubuntu
sudo dnf install conky # RHEL/CentOS
Create a basic Conky configuration for CPU monitoring:
conky.config = {
alignment = 'top_right',
background = false,
border_width = 1,
cpu_avg_samples = 2,
default_color = 'white',
default_outline_color = 'white',
default_shade_color = 'white',
double_buffer = true,
draw_borders = false,
draw_graph_borders = true,
draw_outline = false,
draw_shades = false,
use_xft = true,
font = 'DejaVu Sans Mono:size=12',
gap_x = 5,
gap_y = 60,
minimum_height = 5,
minimum_width = 5,
net_avg_samples = 2,
no_buffers = true,
out_to_console = false,
out_to_ncurses = false,
out_to_stderr = false,
out_to_x = true,
extra_newline = false,
own_window = true,
own_window_class = 'Conky',
own_window_type = 'desktop',
stippled_borders = 0,
update_interval = 1.0,
uppercase = false,
use_spacer = 'none',
show_graph_scale = false,
show_graph_range = false
}
conky.text = [[
${color grey}CPU Usage:$color ${cpu}% ${cpubar 4}
${cpugraph 60,300}
]]
Save this configuration to ~/.conkyrc and run Conky:
conky
4. Advanced Techniques
4.1. sar for Historical Analysis
The System Activity Reporter (sar) is part of the sysstat package and allows for historical CPU usage analysis.
Enable data collection by editing /etc/default/sysstat:
ENABLED="true"
Restart the sysstat service:
sudo systemctl restart sysstat
To view yesterday’s CPU usage:
sar -u -f /var/log/sa/sa$(date -d yesterday +%d)
4.2. Automated Alert Systems
Create a simple bash script to alert you when CPU usage exceeds a threshold:
#!/bin/bash
threshold=90
current=$(top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}')
if (( $(echo "$current > $threshold" | bc -l) )); then
echo "Alert: CPU usage at $current%" | mail -s "High CPU Alert" admin@example.com
fi
Save this script and make it executable:
chmod +x cpu_alert.sh
Add it to your crontab to run every 5 minutes:
*/5 * * * * /path/to/cpu_alert.sh
5. Troubleshooting High CPU Usage
5.1. Identifying Culprit Processes
Use pidstat to identify processes consuming high CPU:
pidstat 1
For kernel-level analysis, use perf:
sudo perf top
5.2. Common Fixes
To restart a service consuming high CPU:
sudo systemctl restart service_name
Limit CPU usage for a process using cgroups:
sudo systemd-run --scope -p CPUQuota=50% command_to_run
Adjust kernel parameters in /etc/sysctl.conf
for system-wide optimizations.
6. Best Practices
- Establish baseline CPU usage during normal operations
- Monitor CPU usage regularly, not just during issues
- Use a combination of real-time and historical monitoring tools
- Correlate CPU usage with other metrics (memory, I/O, network)
- Document normal usage patterns and investigate deviations
7. Conclusion
Monitoring CPU usage on Linux systems is a critical skill for maintaining optimal performance. From simple command-line tools like top to advanced graphical solutions, Linux provides a rich ecosystem of monitoring utilities. By regularly checking CPU usage, understanding the metrics, and knowing how to troubleshoot high utilization, you can ensure your Linux systems run efficiently and reliably.
Remember to establish baselines, use a combination of real-time and historical monitoring, and correlate CPU usage with other system metrics for a comprehensive view of your system’s health. With the knowledge and tools provided in this guide, you’re well-equipped to keep your Linux machines running at peak performance.