in

How to Monitor CPU and Memory Usage on Linux

As a Linux system administrator, being able to monitor CPU and memory usage is crucial for identifying performance bottlenecks and troubleshooting issues. In this comprehensive guide, we will explore the various tools and techniques for monitoring CPU and memory utilization on Linux systems.

Why Monitoring Usage Matters

Before jumping into the tools, let‘s discuss why monitoring CPU and memory utilization is so important for any Linux admin.

Identify Resource Hogs

By keeping an eye on per-process CPU and memory stats, you can quickly identify any processes that are chewing up disproportionate amounts of resources. This helps troubleshoot poorly optimized or runaway programs.

Detect Memory Leaks

Monitoring memory usage over time can reveal memory leaks in applications that fail to release allocated RAM. This is critical as memory leaks eventually lead to out-of-memory issues.

Understand Trends

Historic utilization data allows you to analyze trends in CPU and memory usage. You can use this for forecasting future capacity requirements.

Troubleshoot Performance

When servers and applications run slow, high CPU or memory usage is often the culprit. Monitoring helps correlate and pinpoint the source of performance problems.

Get Alerts

You can configure alerting thresholds on utilization metrics to proactively notify you when certain limits are crossed. This enables troubleshooting before issues impact users.

As you can see, monitoring CPU and RAM usage provides valuable insights into the health, performance and capacity needs of your systems. Now let‘s look at how to track utilization on Linux.

Top Tools for Monitoring CPU Usage

Linux offers several excellent command-line tools for monitoring current and historical CPU usage. Let‘s discuss some of the most popular options:

top – Real-time Process Viewer

The top program offers a dynamic real-time view of overall system activity and the resource consumption of processes:

top

The top section provides a compact overview of total CPU usage broken down by different categories:

  • us – Time spent in user space.
  • sy – Time executing kernel code.
  • ni – Time handling interrupts.
  • id – Idle time when the CPU has no work.
  • wa – I/O wait time.
  • hi – Time handling hardware interrupts.
  • si – Time handling software interrupts.
  • st – Time stolen from a virtual machine.

The %Cpu(s) row shows the CPU usage percentage split across all cores.

The %Cpu column for each process lists its CPU usage as a percentage of total available CPU time.

top lets you interactively sort processes by CPU usage and monitor consumption in real-time with a refresh every few seconds.

htop – Improved top

htop is an enhanced, user-friendly version of top featuring a better looking interface and interactive menus:

htop

Install htop:

sudo apt install htop # Debian/Ubuntu
sudo yum install htop # RHEL/CentOS

htop shows the same critical CPU usage metrics as top, in a polished interface with colors for easier analysis.

mpstat – Per-Processor Statistics

The mpstat tool from sysstat package reports utilization statistics per processor core. This helps provide granular visibility on multi-core systems.

View per-core CPU usage:

mpstat -P ALL 5

This outputs utilization per available core refreshed every 5 seconds.

pidstat – Per-Process CPU

pidstat from sysstat package can report on CPU usage by process ID or command name:

pidstat -p 1234 -u 5

This shows CPU usage every 5 seconds for process ID 1234.

pidstat -C php-fpm 5 

Prints usage for the php-fpm process name.

sar – Historic Statistics

The sar tool collects and reports historic stats for CPU, memory, disks, network and other resources.

It reads utilization data from the daily log files in /var/log/sa. To enable sar, install the sysstat package:

sudo apt install sysstat #Debian/Ubuntu
sudo yum install sysstat #RHEL/CentOS

This configures the sadd background daemon to collect metrics.

To view historic CPU statistics:

sar -u

You can also extract specific time ranges like:

sar -u 13:00:00 13:10:00 #CPU usage from 13:00-13:10

sar provides invaluable historical performance and capacity trending information.

Top Tools for Monitoring Memory Usage

In addition to CPU, monitoring memory usage is also super important. Linux once again provides great command-line tools for this:

free – Available Memory

The simplest way to view memory utilization is the free command:

free -h

This shows total system memory, used memory, free memory, in human readable units (e.g. GB).

The -m flag displays output in MB instead of bytes.

/proc/meminfo – Detailed Memory Metrics

The Linux kernel exposes a wide array of memory usage metrics under /proc/meminfo.

Grepping this provides low-level visibility into RAM utilization:

grep MemTotal /proc/meminfo
grep MemAvailable /proc/meminfo

Helpful fields include:

  • MemTotal: Total installed RAM
  • MemFree: Unused memory
  • MemAvailable: Available memory for new processes
  • Buffers/Cached: File buffer cache usage
  • SwapTotal: Total swap space
  • SwapFree: Unused swap usage

htop – Interactive Process Viewer

The htop tool shows memory utilization in a user-friendly interactive interface:

htop memory

It displays total memory, used, available, swap etc.

top – Real-time Process Table

The top program also includes high-level memory stats:

top

Keep an eye on the KiB Mem and KiB Swap lines for overall usage.

Tracking Per-Process Usage

While system-wide monitoring is useful, often you need deeper visibility into resource consumption of individual processes. Granular per-process metrics help uncover specific programs that are bogging down your servers.

htop – Interactive Process Viewer

One of the best ways to see per-process CPU and memory stats is htop:

htop process

The CPU% and MEM% columns show utilization by each process/command.

You can interactively sort by CPU/RAM usage and filter the process list.

top – Real-time Process Table

Similarly, the top command shows per-process usage:

top

The %CPU and %MEM columns display utilization for each running process.

ps – Snapshot Process Usage

The ps tool also reveals usage with the aux or ef options:

ps aux --sort=-%cpu
ps ef --sort=-%mem 

This prints a one-time snapshot of processes sorted by CPU or memory utilization.

pidstat – Process CPU Statistics

As seen earlier, pidstat from the sysstat package can report CPU usage for a specific process ID or name:

pidstat -p 1234 -u 5
pidstat -C nginx 5

pmap – Process Memory Map

The pmap command prints out the memory map of a running process. This helps understand the memory footprint per-process.

pmap 1234

Prints memory usage statistics of process ID 1234.

Graphical System Monitors

While terminal-based tools are great, sometimes you need a graphical bird‘s eye view of what‘s happening on your system. Some useful GUI monitors include:

uptime

A simple terminal-based resource monitor. Shows load average, uptime, users, and utilization stats in a compact interface.

saidar

Saidar provides terminal-based dashboard with utilizations graphs and metrics for CPU, memory, disks, network etc.

nmon – Ncurses System Monitor

nmon has an interactive terminal UI with graphs and process information:

nmon

TUI stands for "Text User Interface".

netdata – Web Dashboard

Netdata is a hugely powerful web-based real-time monitoring solution. It presents metrics through customizable dashboards with interactive graphs and alarms.

netdata dashboard

Netdata installation instructions are available in this guide.

webmin – Web GUI for Linux

Webmin provides a web interface for controlling many Linux administrator tasks. Its System and Process Status modules allow quick graphical monitoring of CPU, memory and disk utilization.

Alerts and Notifications

While active monitoring is great, you also want proactive alerts when certain utilization thresholds are crossed or issues are detected.

Some useful alerting tools include:

Monitorix

Monitorix allows configuring alert thresholds for CPU, memory, disk space, load average and more. It can notify you via email, Slack etc.

Monit

Monit can monitor resources usage and send you alerts when defined limits are exceeded.

netdata

Netdata allows setting alarms on every metric it tracks. You can get notifications for high CPU, RAM, or any other utilization metric.

NfSen/NfSenNG

NfSen and NfSenNG provide a web UI and reporting platform for NetFlow data. This allows alerting on bandwidth usage.

Collectd

Collectd is a plugin-based metric collection daemon. It supports notification plugins to send alerts for metrics like CPU load.

Final Thoughts

Monitoring CPU and memory utilization provides invaluable visibility into Linux system health, performance and capacity.

Mastering tools like top, htop, vmstat, sar allows you to quickly detect issues and identify resource bottlenecks. Combining terminal monitors with graphical dashboards provides both high-level and granular views.

I hope this guide offered you a comprehensive overview of the most essential CPU and memory monitoring tools on Linux. Let me know if you have any other favorite utilization tracking tips or tricks!

AlexisKestler

Written by Alexis Kestler

A female web designer and programmer - Now is a 36-year IT professional with over 15 years of experience living in NorCal. I enjoy keeping my feet wet in the world of technology through reading, working, and researching topics that pique my interest.