[How-to] Monitor CPU & Memory Usage on Linux
Table of Contents
- Introduction
- Monitor CPU and Memory Usage with the top Command
- Monitor CPU and Memory Usage with htop Command
- Monitor Memory Usage with free Command
- Monitor CPU and Memory Usage with vmstat
- Monitor CPU and Memory Usage of Processes with ps
- Advanced CPU and Memory Usage Monitoring with sar
- Troubleshooting CPU and Memory Usage Issues
- Advanced CPU and Memory Monitoring Examples
- CPU and Memory Usage Optimization Tips
- Comparing CPU and Memory Monitoring Tools
- Best Practices
- Conclusion
Introduction
Monitoring CPU and memory usage is essential for maintaining optimal system performance, identifying resource bottlenecks, and troubleshooting performance issues on Linux systems. Whether you’re a system administrator managing servers or a developer optimizing applications, understanding how to monitor these critical resources helps ensure your system runs efficiently. This guide will teach you how to monitor CPU and memory usage effectively using various command-line tools available on Linux distributions, with practical examples using Ubuntu Server 24.04 LTS. For more information on Ubuntu system administration, refer to the official Ubuntu server documentation.
Monitor CPU and Memory Usage with the top Command
The top command provides a real-time, dynamic view of system processes and resource usage. It’s one of the most commonly used tools for monitoring CPU and memory consumption. This allows you to monitor CPU and memory usage in real-time effectively. Moreover, for detailed information about top, refer to the top man page.
Basic Usage
To start monitoring with top, simply run the command:
lc-root@ubuntu:~$ top
This displays a continuously updating list of processes sorted by CPU usage by default. The top section shows system summary information including:
- System uptime and load average
- Total number of tasks
- CPU usage percentages (user, system, idle, etc.)
- Memory and swap usage
Interactive Commands
While top is running, you can use various keyboard shortcuts:
Shift+P: Sort by CPU usageShift+M: Sort by memory usage1: Show individual CPU coresh: Display helpq: Quit
Monitor CPU and Memory Usage with htop Command
htop is an enhanced, interactive process viewer that provides a more user-friendly interface compared to top, with color coding and mouse support. Moreover, htop provides enhanced CPU and memory monitoring capabilities compared to the basic top command.
Installation
First, ensure your package list is up to date and install htop:
lc-root@ubuntu:~$ sudo apt update lc-root@ubuntu:~$ sudo apt install htop
Basic Usage
Launch htop with:
lc-root@ubuntu:~$ htop
htop displays processes in a hierarchical tree view by default and provides additional features like:
- Color-coded resource usage bars
- Mouse support for selecting and interacting with processes
- Vertical and horizontal scrolling
- Process filtering and searching
Navigation and Features
Use the following keys in htop:
F1: HelpF2: Setup (configure meters and columns)F3: Search for processesF4: Filter processesF5: Tree viewF6: Sort by columnF9: Kill processF10orq: Quit
Monitor Memory Usage with free Command
The free command displays information about system memory usage, including RAM and swap space. The free command is essential for monitoring memory usage on Linux systems. Additionally, for detailed information, refer to the free man page.
Basic Usage
Check memory usage with:
lc-root@ubuntu:~$ free
For more readable output in human-friendly units:
lc-root@ubuntu:~$ free -h
The output shows:
total: Total installed memoryused: Memory currently in usefree: Unused memoryshared: Memory used by tmpfsbuff/cache: Memory used for buffers and cacheavailable: Estimated memory available for new processes
Continuous Monitoring
To monitor memory usage continuously:
lc-root@ubuntu:~$ free -h -s 5
This updates the display every 5 seconds.
Monitor CPU and Memory Usage with vmstat
vmstat reports virtual memory statistics and provides information about processes, memory, paging, block I/O, traps, and CPU activity. vmstat is another powerful tool for monitoring CPU and memory usage statistics in real-time. Furthermore, for detailed information, refer to the vmstat man page.
Basic Usage
Get a snapshot of current system statistics:
lc-root@ubuntu:~$ vmstat
Continuous Monitoring
For real-time monitoring with updates every second:
lc-root@ubuntu:~$ vmstat 1
The output includes:
procs: Process statistics (r: running, b: blocked)memory: Memory usage (swpd: swapped, free: free, buff: buffers, cache: cache)swap: Swap space usage (si: swap in, so: swap out)io: I/O statistics (bi: blocks in, bo: blocks out)system: System statistics (in: interrupts, cs: context switches)cpu: CPU usage percentages
Monitor CPU and Memory Usage of Processes with ps
The ps command displays information about active processes, useful for identifying resource-intensive processes. The ps command helps in monitoring CPU and memory usage of individual processes. Also, for detailed information, refer to the ps man page.
View All Processes
Display all processes with detailed information:
lc-root@ubuntu:~$ ps aux
Sort by CPU Usage
Find processes consuming the most CPU:
lc-root@ubuntu:~$ ps aux --sort=-%cpu | head -10
Sort by Memory Usage
Find processes using the most memory:
lc-root@ubuntu:~$ ps aux --sort=-%mem | head -10
Monitor Specific Process
Monitor a specific process by PID:
lc-root@ubuntu:~$ ps -p 1234 -o pid,ppid,cmd,%cpu,%mem
Advanced CPU and Memory Usage Monitoring with sar
sar (System Activity Reporter) collects and reports system activity information, providing historical data and detailed statistics. sar enables advanced monitoring of CPU and memory usage with historical data collection. However, for detailed information, refer to the sar man page.
Installation
Install the sysstat package which includes sar:
lc-root@ubuntu:~$ sudo apt update lc-root@ubuntu:~$ sudo apt install sysstat
CPU Monitoring
Monitor CPU usage with 1-second intervals for 5 iterations:
lc-root@ubuntu:~$ sar -u 1 5
Memory Monitoring
Monitor memory usage:
lc-root@ubuntu:~$ sar -r 1 5
View Historical Data
View CPU statistics from yesterday:
lc-root@ubuntu:~$ sar -u -f /var/log/sysstat/sa$(date -d yesterday +%d)
Troubleshooting CPU and Memory Usage Issues
When monitoring CPU and memory usage, you may encounter various issues that require troubleshooting. Here are some common problems and their solutions:
High CPU Usage Issues
If you notice unusually high CPU usage, investigate the following:
- Identify CPU-intensive processes: Use
toporps aux --sort=-%cpu | head -10to find processes consuming excessive CPU - Check for runaway processes: Look for processes with increasing CPU usage over time
- Monitor system load: Use
uptimeorcat /proc/loadavgto check system load averages - Check for hardware issues: High CPU usage might indicate cooling problems or failing hardware
Memory Usage Problems
Memory-related issues can significantly impact system performance:
- Out of memory errors: Monitor for OOM (Out of Memory) killer activity in system logs
- Memory leaks: Use
valgrindor similar tools to detect memory leaks in applications - Swap usage: Excessive swap usage can slow down the system; monitor with
free -h - Cache management: Understand the difference between buffer and cache memory usage
Monitoring Tool Issues
Sometimes the monitoring tools themselves may have issues:
- htop not found: Ensure htop is installed with
sudo apt install htop - sar data not available: Check if sysstat service is running with
systemctl status sysstat - Permission denied: Some commands may require root privileges; use
sudowhen necessary - Inaccurate readings: Compare outputs from multiple tools to verify accuracy
Advanced CPU and Memory Monitoring Examples
Beyond basic monitoring, these advanced examples show how to combine tools for comprehensive system analysis.
Creating Monitoring Scripts
Create a simple monitoring script that logs system statistics:
lc-root@ubuntu:~$ cat > monitor_system.sh << 'EOF' #!/bin/bash echo "=== System Monitoring Report ===" echo "Timestamp: $(date)" echo "" echo "CPU Usage:" top -bn1 | head -10 echo "" echo "Memory Usage:" free -h echo "" echo "Disk Usage:" df -h echo "" echo "Top 5 CPU Processes:" ps aux --sort=-%cpu | head -6 echo "" echo "Top 5 Memory Processes:" ps aux --sort=-%mem | head -6 EOF lc-root@ubuntu:~$ chmod +x monitor_system.sh lc-root@ubuntu:~$ ./monitor_system.sh
Real-time Monitoring with Watch
Use the watch command for continuous monitoring:
lc-root@ubuntu:~$ watch -n 2 'echo "CPU and Memory Usage:"; uptime; free -h; echo ""; echo "Top Processes:"; ps aux --sort=-%cpu | head -5'
This updates the display every 2 seconds with current system statistics.
Logging System Statistics
Set up automated logging of system performance:
lc-root@ubuntu:~$ crontab -e # Add this line to log system stats every 5 minutes */5 * * * * /usr/bin/vmstat 1 5 >> /var/log/system_stats_$(date +\%Y\%m\%d).log 2>&1
CPU and Memory Usage Optimization Tips
Based on monitoring data, here are strategies to optimize system performance:
CPU Optimization
- Process prioritization: Use
niceandreniceto adjust process priorities - CPU affinity: Bind processes to specific CPU cores using
taskset - Interrupt handling: Monitor and optimize interrupt requests with
vmstat - Multithreading: Ensure applications are properly utilizing multiple CPU cores
Memory Optimization
- Memory limits: Set memory limits for processes using
ulimitor cgroups - Swap configuration: Optimize swap space size and swappiness settings
- Cache management: Monitor and manage filesystem cache with
vmtouch - Memory defragmentation: Use tools like
jemallocfor better memory allocation
System-wide Optimizations
- Kernel parameters: Tune kernel parameters in
/etc/sysctl.conf - Service management: Disable unnecessary services to free up resources
- Filesystem optimization: Choose appropriate filesystems and mount options
- Network tuning: Optimize network stack parameters for better performance
Comparing CPU and Memory Monitoring Tools
Each monitoring tool has its strengths and use cases:
Real-time Monitoring
- top: Best for quick overview, lightweight, always available
- htop: Enhanced interface, better for interactive monitoring
- vmstat: Detailed system statistics, good for scripting
Memory-specific Monitoring
- free: Simple memory overview, perfect for quick checks
- vmstat: Detailed memory statistics including swap activity
- sar -r: Historical memory usage trends
Process Analysis
- ps: Detailed process information, great for scripting
- top/htop: Real-time process monitoring with sorting options
- pgrep/pkill: Process selection and management
Historical Analysis
- sar: Comprehensive historical data collection
- sysstat: Automated logging and reporting
- Custom scripts: Tailored logging solutions
Best Practices
Follow these professional recommendations for effective system monitoring:
- Regular Monitoring: Establish routine monitoring schedules to identify trends and potential issues before they become critical
- Baseline Establishment: Understand normal system behavior during peak and off-peak hours to better identify anomalies
- Alert Configuration: Set up automated alerts for CPU usage above 80% or memory usage above 90% using tools like Nagios or Zabbix
- Resource Planning: Use monitoring data to plan hardware upgrades or optimize application performance
- Documentation: Keep records of monitoring findings and resolution steps for future reference
- Security Considerations: Monitor for unusual processes that might indicate security breaches or malware activity
- Tool Combination: Use multiple tools together for comprehensive monitoring coverage
- Automation: Implement automated monitoring scripts and alerts for proactive system management
- Historical Data: Maintain logs of system performance for trend analysis and capacity planning
- Regular Review: Periodically review and update monitoring practices as system requirements change
Conclusion
Effective monitoring of CPU and memory usage is fundamental to maintaining healthy Linux systems. The tools covered in this guide - top, htop, free, vmstat, ps, and sar - provide comprehensive insights into system performance from basic real-time monitoring to advanced historical analysis. By regularly monitoring these resources and following best practices, you can ensure optimal system performance, prevent downtime, and quickly identify and resolve performance issues. Start with basic tools like top and free, then explore advanced options like sar for more detailed analysis as your monitoring needs grow. Furthermore, for related Linux administration topics, check out our guides on getting MAC addresses on Linux and mastering IP addressing and subnet calculation.