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 processor is performing helps identify bottlenecks, troubleshoot performance issues, and optimize system resources. This comprehensive guide will walk you through various methods to check CPU usage in Linux, from basic commands to advanced monitoring techniques. Why Monitor CPU Usage? CPU monitoring serves several critical purposes: - Performance Optimization: Identify resource-intensive processes consuming excessive CPU time - Troubleshooting: Diagnose system slowdowns and application performance issues - Capacity Planning: Determine when hardware upgrades are necessary - Security: Detect unusual process activity that might indicate malware or security breaches - System Health: Maintain overall system stability and prevent crashes Understanding CPU Metrics Before diving into the commands, it's essential to understand key CPU metrics: - User Time: CPU time spent executing user processes - System Time: CPU time spent in kernel mode executing system calls - Idle Time: Percentage of time the CPU spends idle - Wait Time: Time spent waiting for I/O operations to complete - Load Average: Average system load over 1, 5, and 15-minute intervals Method 1: Using the `top` Command The `top` command is the most commonly used tool for real-time CPU monitoring in Linux. Basic Usage ```bash top ``` This displays a dynamic view of running processes, sorted by CPU usage by default. The output includes: ``` top - 14:30:45 up 2 days, 3:42, 2 users, load average: 0.15, 0.25, 0.18 Tasks: 245 total, 2 running, 243 sleeping, 0 stopped, 0 zombie %Cpu(s): 5.2 us, 2.1 sy, 0.0 ni, 92.5 id, 0.2 wa, 0.0 hi, 0.0 si, 0.0 st MiB Mem : 7854.2 total, 2156.3 free, 3247.8 used, 2450.1 buff/cache MiB Swap: 2048.0 total, 2048.0 free, 0.0 used. 4151.2 avail Mem PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 12345 john 20 0 123456 45678 9876 R 25.0 5.8 0:15.23 firefox 5678 root 20 0 67890 12345 6789 S 10.0 1.6 1:23.45 systemd ``` Key Information from Top Output - Load Average: Shows system load over 1, 5, and 15 minutes - CPU Line: Displays percentage breakdown of CPU usage - Process List: Individual processes with their CPU consumption Useful Top Options ```bash Update every 2 seconds top -d 2 Show only processes for a specific user top -u username Display specific number of processes top -n 1 Sort by memory usage instead of CPU top -o %MEM ``` Interactive Commands in Top While `top` is running, you can use these keyboard shortcuts: - `1`: Toggle between overall CPU stats and per-core stats - `P`: Sort by CPU usage (default) - `M`: Sort by memory usage - `k`: Kill a process by PID - `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 ```bash Ubuntu/Debian sudo apt install htop CentOS/RHEL/Fedora sudo yum install htop or sudo dnf install htop Arch Linux sudo pacman -S htop ``` Basic Usage ```bash htop ``` `htop` provides: - Color-coded display - Mouse support - Tree view of processes - Horizontal scrolling - Better process filtering Htop Features - F1: Help - F2: Setup/configuration - F3: Search processes - F4: Filter processes - F5: Tree view - F6: Sort by different columns - F9: Kill process - F10: Quit Method 3: Using `vmstat` Command `vmstat` provides detailed system statistics including CPU usage, memory, and I/O information. Basic Usage ```bash Single snapshot vmstat Continuous monitoring (update every 2 seconds) vmstat 2 Monitor for specific duration (5 updates every 2 seconds) vmstat 2 5 ``` Sample 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 2156324 245632 2450112 0 0 12 25 85 142 5 2 92 1 0 ``` CPU Columns Explained - us: User time (user processes) - sy: System time (kernel processes) - id: Idle time - wa: Wait time (I/O wait) - st: Stolen time (virtual environments) Method 4: Using `iostat` Command `iostat` is part of the `sysstat` package and provides CPU and I/O statistics. Installation ```bash Ubuntu/Debian sudo apt install sysstat CentOS/RHEL/Fedora sudo yum install sysstat ``` Basic Usage ```bash Single report iostat Continuous monitoring (every 2 seconds) iostat 2 CPU-only statistics iostat -c Extended statistics iostat -x ``` Sample CPU Output ``` avg-cpu: %user %nice %system %iowait %steal %idle 5.23 0.00 2.15 0.25 0.00 92.37 ``` Method 5: Using `sar` Command The `sar` (System Activity Reporter) command is another component of the `sysstat` package. Basic Usage ```bash Current CPU usage sar -u Monitor every 2 seconds for 10 intervals sar -u 2 10 Show per-CPU core statistics sar -P ALL Historical data (if available) sar -u -f /var/log/sysstat/saXX ``` Sample Output ``` 03:00:01 PM CPU %user %nice %system %iowait %steal %idle 03:10:01 PM all 5.24 0.00 2.18 0.28 0.00 92.30 ``` Method 6: Using `/proc/stat` File For scripting purposes, you can directly read CPU information from the `/proc/stat` file. Reading CPU Information ```bash Display raw CPU statistics cat /proc/stat | grep "^cpu" First line shows overall CPU statistics head -n 1 /proc/stat ``` Sample Output ``` cpu 12345 678 9012 345678 901 0 234 0 0 0 ``` The numbers represent: 1. User time 2. Nice time 3. System time 4. Idle time 5. I/O wait time 6. Hardware interrupt time 7. Software interrupt time 8. Steal time 9. Guest time 10. Guest nice time Method 7: Using `ps` Command The `ps` command can show CPU usage for specific processes. Basic Usage ```bash Show CPU usage for all processes ps aux --sort=-%cpu Top 10 CPU-consuming processes ps aux --sort=-%cpu | head -n 11 Monitor specific process ps -p PID -o pid,ppid,cmd,%cpu,%mem Show CPU usage over time for a process watch "ps -p PID -o pid,ppid,cmd,%cpu,%mem" ``` Method 8: Using `nmon` Command `nmon` provides a comprehensive system monitor with an interactive interface. Installation ```bash Ubuntu/Debian sudo apt install nmon CentOS/RHEL sudo yum install nmon ``` Basic Usage ```bash nmon ``` Interactive keys: - `c`: CPU statistics - `m`: Memory statistics - `d`: Disk statistics - `n`: Network statistics - `q`: Quit Real-World Monitoring Scenarios Scenario 1: Identifying CPU-Intensive Processes ```bash Find top 5 CPU consumers ps aux --sort=-%cpu | head -n 6 Monitor them continuously watch "ps aux --sort=-%cpu | head -n 6" ``` Scenario 2: Monitoring Server Performance ```bash Comprehensive monitoring #!/bin/bash echo "=== CPU Usage ===" vmstat 1 5 echo "=== Top Processes ===" ps aux --sort=-%cpu | head -n 10 echo "=== Load Average ===" uptime ``` Scenario 3: Historical Analysis ```bash Generate daily CPU report sar -u -s 00:00:00 -e 23:59:59 > cpu_report_$(date +%Y%m%d).txt ``` Advanced CPU Monitoring Techniques Using `mpstat` for Multi-Core Systems ```bash Show per-CPU statistics mpstat -P ALL Monitor every 2 seconds mpstat -P ALL 2 JSON output for parsing mpstat -o JSON 2 3 ``` Creating Custom Scripts ```bash #!/bin/bash cpu_monitor.sh - Simple CPU monitoring script while true; do echo "$(date): $(cat /proc/loadavg)" sleep 60 done >> cpu_usage.log ``` Using `dstat` for Comprehensive Monitoring ```bash Install dstat sudo apt install dstat # Ubuntu/Debian Monitor CPU, memory, disk, and network dstat -c -m -d -n Custom format dstat --cpu --mem --disk --net --time ``` Troubleshooting Common Issues High CPU Usage Problems 1. Identify the culprit: ```bash top -o %CPU ``` 2. Check for runaway processes: ```bash ps aux | awk '$3 > 50 {print $0}' ``` 3. Monitor system load: ```bash uptime watch uptime ``` Performance Bottlenecks 1. Check I/O wait: ```bash iostat -x 1 ``` 2. Monitor context switches: ```bash vmstat 1 ``` 3. Analyze process states: ```bash ps aux | awk '{print $8}' | sort | uniq -c ``` Memory vs CPU Issues ```bash Check if high CPU is due to memory pressure free -h vmstat 1 5 Look for swapping activity sar -W 1 10 ``` Best Practices for CPU Monitoring Regular Monitoring Routine 1. Daily Checks: - Quick `top` or `htop` review - Check load averages with `uptime` - Review system logs for anomalies 2. Weekly Analysis: - Generate `sar` reports - Analyze trends and patterns - Document any recurring issues 3. Monthly Planning: - Review capacity requirements - Plan for scaling or upgrades - Update monitoring scripts Automation and Alerting ```bash #!/bin/bash Simple CPU alert script THRESHOLD=80 CURRENT=$(top -bn1 | grep "Cpu(s)" | sed "s/., \([0-9.]\)% id.*/\1/" | awk '{print 100 - $1}') if (( $(echo "$CURRENT > $THRESHOLD" | bc -l) )); then echo "High CPU usage: ${CURRENT}%" | mail -s "CPU Alert" admin@example.com fi ``` Performance Tuning Tips CPU Optimization Strategies 1. Process Priority Management: ```bash # Lower priority for CPU-intensive tasks nice -n 19 cpu_intensive_command # Adjust running process priority renice -n 10 -p PID ``` 2. CPU Affinity: ```bash # Bind process to specific CPU cores taskset -c 0,1 command # Check current affinity taskset -p PID ``` 3. System Tuning: ```bash # Check CPU frequency scaling cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor # Set performance governor echo performance | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor ``` Conclusion Monitoring CPU usage in Linux is essential for maintaining optimal system performance. The variety of tools available—from basic commands like `top` and `ps` to advanced utilities like `sar` and `iostat`—provides comprehensive insights into your system's CPU utilization. Key takeaways: - Use `top` or `htop` for real-time interactive monitoring - Leverage `vmstat` and `iostat` for detailed system statistics - Implement `sar` for historical analysis and reporting - Create custom scripts for automated monitoring and alerting - Regular monitoring helps prevent performance issues and plan for capacity needs By mastering these tools and techniques, you'll be well-equipped to diagnose performance issues, optimize system resources, and maintain healthy Linux systems. Remember that effective CPU monitoring is not just about using the right tools—it's about understanding the data they provide and taking appropriate action based on your findings. Start with the basic commands and gradually incorporate more advanced techniques as your monitoring needs grow. Regular practice with these tools will make you proficient in Linux system performance analysis and optimization.