Understanding CPU/Memory Consumption with the top Command
Monitoring system performance is crucial for effective resource management, and the top
command in Linux is an excellent tool for real-time monitoring of system processes. It provides insights into which processes are consuming the most CPU and memory, helping you optimize system performance.
Basics of top
Running top
without any arguments shows a list of processes, updated in real-time. It’s the go-to tool for understanding system load and performance bottlenecks.
top
This displays a dynamic view of system processes, sorted by CPU usage. By default, it shows the following key columns:
PID: Process ID.
USER: Owner of the process.
%CPU: Percentage of CPU usage.
%MEM: Percentage of physical memory usage.
COMMAND: The name of the task.
Filtering by CPU/Memory
If you’re specifically interested in processes hogging CPU and memory, you can modify the view. The top
command allows you to sort processes by CPU and memory consumption using these shortcuts:
Shift + p: Sort by CPU usage.
Shift + m: Sort by memory usage.
Displaying Specific Process Information
To view a specific process by its PID:
top -n 1 -b -p <pid>
This command displays detailed information about a single process, which is useful when troubleshooting a specific application.
Saving the Output
Sometimes, you may want to capture the output for later analysis:
top -n 1 -b > top.txt
This saves a snapshot of all running processes into a file.
Memory Usage Breakdown
The top
command provides essential memory stats such as RSS (Resident Set Size) which shows how much physical memory a process is using, and SIZE, which shows the total memory allocated. To calculate the total memory in use by all processes, you can use the following command:
echo `echo '0 ' ; top -q -n 1 -b | sed -e '1,/PID *USER *PRI/D' | \
awk '{print "+" $6}' | sed -e 's/M/\\*1024/'` | bc
This command will give you the total memory consumption of all processes, converting it to kilobytes.
Useful top
Options
Here are some key interactive commands you can use within top
:
f: Alter the fields displayed.
r: Renice a process (change its priority).
k: Kill a process by specifying its PID.
Conclusion
The top
command is a versatile tool for monitoring real-time CPU and memory consumption. By using its interactive commands and filters, you can keep your system running smoothly, ensuring resources are being allocated efficiently.
Subscribe to my newsletter
Read articles from Mahesh Gaikwad directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by