How to check CPU usage in Linux

How to Check CPU Usage in Linux Monitoring CPU usage is a fundamental skill for Linux system administrators, developers, and power users. Understanding how your system's processor is being utilized helps you identify performance bottlenecks, troubleshoot system issues, and optimize resource allocation. This comprehensive guide will walk you through various methods to check CPU usage in Linux, from basic command-line tools to advanced monitoring techniques. Whether you're managing a single desktop system or multiple servers, knowing how to effectively monitor CPU performance is crucial for maintaining optimal system health and performance. This article covers everything from simple one-time checks to continuous monitoring solutions, ensuring you have the right tool for every situation. Prerequisites and Requirements Before diving into CPU monitoring techniques, ensure you have: - Linux System Access: Any modern Linux distribution (Ubuntu, CentOS, RHEL, Debian, etc.) - Terminal Access: Command-line interface with basic navigation skills - User Permissions: Most commands work with regular user privileges, though some advanced features may require root access - Basic Linux Knowledge: Understanding of processes, system resources, and command-line operations System Requirements - Linux kernel version 2.6 or higher (most modern distributions) - Sufficient terminal width for optimal display of monitoring tools - Network access if you plan to install additional monitoring packages Understanding CPU Metrics Before exploring monitoring tools, it's essential to understand key CPU metrics: - User Time (%us): Time spent running user processes - System Time (%sy): Time spent in kernel space - Nice Time (%ni): Time spent running niced user processes - Idle Time (%id): Time when CPU is idle - I/O Wait (%wa): Time waiting for I/O operations to complete - Hardware Interrupts (%hi): Time handling hardware interrupts - Software Interrupts (%si): Time handling software interrupts - Steal Time (%st): Time stolen by virtualization (in virtual environments) Method 1: Using the `top` Command The `top` command is the most widely available and commonly used tool for monitoring CPU usage in real-time. Basic Usage ```bash top ``` This displays a dynamic view of running processes, with CPU usage information updated every few seconds. The header shows overall system CPU statistics, while individual processes are listed below with their respective CPU consumption. Understanding Top Output The CPU line in top output looks like this: ``` %Cpu(s): 2.3 us, 1.1 sy, 0.0 ni, 96.5 id, 0.1 wa, 0.0 hi, 0.0 si, 0.0 st ``` Useful Top Options Sort by CPU usage: ```bash top -o %CPU ``` Show specific user processes: ```bash top -u username ``` Batch mode for scripting: ```bash top -b -n 1 ``` Display specific number of processes: ```bash top -n 1 | head -20 ``` Interactive Commands Within Top While top is running, use these keys: - `P`: Sort by CPU usage - `M`: Sort by memory usage - `k`: Kill a process - `r`: Renice a process - `q`: Quit top Method 2: Using `htop` Command `htop` is an enhanced version of top with a more user-friendly interface and additional features. Installation Ubuntu/Debian: ```bash sudo apt update sudo apt install htop ``` CentOS/RHEL/Fedora: ```bash sudo yum install htop or for newer versions sudo dnf install htop ``` Basic Usage ```bash htop ``` Key Features of htop - Color-coded display: Different colors for different types of processes - Mouse support: Click to select processes - Tree view: Show process relationships - Multiple CPU cores: Individual core usage display - Easy process management: Kill, renice processes with function keys Htop Advantages - Visual CPU usage bars for each core - Easy navigation with arrow keys - Built-in help (F1 key) - Customizable display columns - Better handling of wide terminal displays Method 3: Using `vmstat` Command `vmstat` provides system statistics including CPU usage, memory, and I/O information. Basic Usage ```bash vmstat ``` Continuous Monitoring ```bash vmstat 2 10 ``` This runs vmstat every 2 seconds for 10 iterations. Understanding vmstat Output ``` procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu----- r b swpd free buff cache si so bi bo in cs us sy id wa st 1 0 0 1234567 89012 345678 0 0 5 10 25 50 2 1 97 0 0 ``` CPU columns explained: - us: User time percentage - sy: System time percentage - id: Idle time percentage - wa: I/O wait percentage - st: Stolen time percentage Method 4: Using `iostat` Command `iostat` is part of the sysstat package and provides detailed CPU and I/O statistics. Installation Ubuntu/Debian: ```bash sudo apt install sysstat ``` CentOS/RHEL: ```bash sudo yum install sysstat ``` Basic CPU Usage ```bash iostat -c ``` Continuous Monitoring ```bash iostat -c 2 5 ``` Detailed CPU Statistics ```bash iostat -c -x 2 ``` Method 5: Using `sar` Command `sar` (System Activity Reporter) is another powerful tool from the sysstat package for collecting and reporting system activity. Basic CPU Usage ```bash sar -u ``` Real-time Monitoring ```bash sar -u 2 10 ``` All CPU Statistics ```bash sar -u ALL 2 5 ``` Historical Data ```bash sar -u -f /var/log/sysstat/saXX ``` Method 6: Using `/proc/stat` File For scripting purposes, you can directly read CPU information from the `/proc/stat` file. Basic Command ```bash cat /proc/stat ``` Extract CPU Information ```bash grep "cpu " /proc/stat ``` Calculate CPU Usage with Script ```bash #!/bin/bash Simple CPU usage calculator cpu_line=$(grep "cpu " /proc/stat) cpu_values=($cpu_line) idle=${cpu_values[4]} total=0 for value in "${cpu_values[@]:1}"; do total=$((total + value)) done usage=$((100 * (total - idle) / total)) echo "CPU Usage: ${usage}%" ``` Method 7: Using `ps` Command The `ps` command can show CPU usage for specific processes. Show All Processes with CPU Usage ```bash ps aux --sort=-%cpu | head -10 ``` Monitor Specific Process ```bash ps -p PID -o pid,ppid,cmd,%cpu,%mem ``` Watch Process CPU Usage ```bash watch -n 2 'ps aux --sort=-%cpu | head -10' ``` Method 8: Using `nmon` Tool `nmon` (Nigel's Monitor) provides comprehensive system monitoring including detailed CPU statistics. Installation Ubuntu/Debian: ```bash sudo apt install nmon ``` Basic Usage ```bash nmon ``` Press 'c' to view CPU statistics and 'q' to quit. Advanced CPU Monitoring Techniques Using `perf` for Performance Analysis ```bash Install perf sudo apt install linux-tools-common linux-tools-generic Monitor CPU events sudo perf top Record CPU usage sudo perf record -g ./your_program sudo perf report ``` Using `cpustat` for Detailed Analysis ```bash Monitor CPU usage with detailed breakdowns sudo cpustat 2 10 ``` Creating Custom Monitoring Scripts ```bash #!/bin/bash Advanced CPU monitoring script while true; do echo "=== CPU Usage Report - $(date) ===" echo "Overall CPU:" vmstat 1 2 | tail -1 | awk '{print "User: "$13"%, System: "$14"%, Idle: "$15"%"}' echo echo "Top 5 CPU consuming processes:" ps aux --sort=-%cpu | head -6 | tail -5 echo "=================================" sleep 10 done ``` Monitoring Multiple CPU Cores View Per-Core Usage with mpstat ```bash Install if not available sudo apt install sysstat Show all CPU cores mpstat -P ALL 2 5 ``` Using htop for Multi-Core Visualization ```bash htop Press F2 → Display options → Detailed CPU time ``` Custom Script for Core Monitoring ```bash #!/bin/bash Monitor individual CPU cores while read line; do if [[ $line == cpu[0-9]* ]]; then echo $line fi done < /proc/stat ``` Setting Up Automated CPU Monitoring Using Cron for Periodic Monitoring ```bash Edit crontab crontab -e Add entry to log CPU usage every 5 minutes /5 * vmstat 1 1 >> /var/log/cpu_usage.log ``` Creating Alerts for High CPU Usage ```bash #!/bin/bash CPU usage alert script THRESHOLD=80 CURRENT=$(vmstat 1 2 | tail -1 | awk '{print 100-$15}') if [ $CURRENT -gt $THRESHOLD ]; then echo "High CPU usage detected: ${CURRENT}%" | mail -s "CPU Alert" admin@example.com fi ``` Troubleshooting Common Issues Issue 1: High CPU Usage Identification Problem: System running slowly with high CPU usage. Solution: ```bash Identify top CPU consumers top -o %CPU Check for specific problematic processes ps aux --sort=-%cpu | head -20 Investigate process details ps -ef | grep process_name ``` Issue 2: Understanding I/O Wait Problem: High I/O wait affecting performance. Solution: ```bash Check I/O wait specifically iostat -x 2 5 Identify processes causing I/O iotop ``` Issue 3: Monitoring in Headless Environments Problem: Need to monitor CPU on servers without GUI. Solution: ```bash Use screen or tmux for persistent monitoring screen -S monitoring htop Or use batch mode for logging top -b -d 5 >> cpu_monitor.log & ``` Issue 4: Permission Denied Errors Problem: Cannot access certain monitoring features. Solution: ```bash Add user to necessary groups sudo usermod -a -G adm username Use sudo for privileged operations sudo iotop sudo perf top ``` Best Practices and Tips 1. Choose the Right Tool for the Task - Quick checks: Use `top` or `htop` - Scripting: Use `vmstat`, `iostat`, or `/proc/stat` - Historical analysis: Use `sar` - Performance tuning: Use `perf` or `nmon` 2. Monitor Trends, Not Just Snapshots ```bash Good: Monitor over time vmstat 5 12 Less useful: Single snapshot vmstat ``` 3. Consider System Context Always correlate CPU usage with: - Memory usage - I/O activity - Network activity - System load average 4. Set Up Baseline Measurements ```bash Create baseline during normal operation sar -u 2 100 > baseline_cpu.log Compare during issues sar -u 2 100 > problem_cpu.log ``` 5. Use Multiple Tools for Verification ```bash Cross-verify with multiple tools top -b -n 1 | head -5 vmstat 1 1 iostat -c 1 1 ``` 6. Automate Monitoring for Production Systems ```bash #!/bin/bash Production monitoring script LOG_FILE="/var/log/system_monitor.log" DATE=$(date '+%Y-%m-%d %H:%M:%S') echo "[$DATE] System Status:" >> $LOG_FILE vmstat 1 1 | tail -1 >> $LOG_FILE echo "Top CPU processes:" >> $LOG_FILE ps aux --sort=-%cpu | head -5 >> $LOG_FILE echo "---" >> $LOG_FILE ``` 7. Understanding Load Average vs CPU Usage ```bash Check load average uptime Compare with actual CPU usage top -b -n 1 | grep "Cpu(s)" ``` Advanced Configuration and Customization Customizing htop Display 1. Run `htop` 2. Press F2 for setup 3. Configure: - Display options - Colors - Columns - Meters Setting Up System-wide Monitoring ```bash Install and configure collectd sudo apt install collectd sudo systemctl enable collectd sudo systemctl start collectd ``` Creating Dashboard Scripts ```bash #!/bin/bash System dashboard script clear echo "=== System Dashboard ===" echo "Date: $(date)" echo echo "CPU Usage:" vmstat 1 2 | tail -1 | awk '{printf "User: %s%%, System: %s%%, Idle: %s%%\n", $13, $14, $15}' echo echo "Load Average:" uptime | awk -F'load average:' '{print $2}' echo echo "Top 5 CPU Processes:" ps aux --sort=-%cpu | head -6 | tail -5 | awk '{printf "%-10s %5s%% %s\n", $1, $3, $11}' ``` Performance Optimization Based on CPU Monitoring Identifying Optimization Opportunities 1. High User Time: Optimize application code 2. High System Time: Check for excessive system calls 3. High I/O Wait: Optimize disk operations or add faster storage 4. High Interrupt Time: Investigate hardware or driver issues Process Priority Management ```bash Lower priority for CPU-intensive tasks nice -n 19 cpu_intensive_task Adjust running process priority renice -n 10 -p PID ``` CPU Affinity Settings ```bash Bind process to specific CPU cores taskset -c 0,1 command Check current CPU affinity taskset -p PID ``` Conclusion Monitoring CPU usage in Linux is essential for maintaining optimal system performance and troubleshooting issues effectively. This comprehensive guide has covered various tools and techniques, from basic commands like `top` and `vmstat` to advanced monitoring solutions using `perf` and custom scripts. Key takeaways include: 1. Multiple Tools Available: Each tool serves specific purposes, from real-time monitoring to historical analysis 2. Context Matters: Always consider CPU usage alongside other system metrics 3. Automation is Key: Set up automated monitoring for production environments 4. Baseline Establishment: Create performance baselines for comparison during issues 5. Continuous Learning: Stay updated with new monitoring tools and techniques Next Steps To further enhance your Linux system monitoring skills: 1. Explore Graphical Tools: Consider tools like Grafana with InfluxDB for visual monitoring 2. Learn Log Analysis: Master log file analysis for deeper system insights 3. Study Performance Tuning: Learn how to optimize based on monitoring data 4. Implement Alerting: Set up proactive alerting systems for critical thresholds 5. Practice Scripting: Develop custom monitoring scripts for specific needs Regular CPU monitoring should become part of your routine system administration tasks. By mastering these tools and techniques, you'll be well-equipped to maintain high-performing Linux systems and quickly identify and resolve performance issues when they arise. Remember that effective monitoring is not just about collecting data, but understanding what the data tells you about your system's health and performance. Use this knowledge to make informed decisions about system optimization, capacity planning, and troubleshooting strategies.