在Linux系统中,有几种方法可以监控CPU使用率。以下是几种常用的方法:
top
命令top
命令是最常用的实时监控工具之一:
top
1
可以显示每个CPU核心的详细信息%Cpu(s)
行显示总体CPU使用情况q
退出htop
命令(更友好的交互式工具)htop
需要先安装:
sudo apt install htop # Debian/Ubuntu
sudo yum install htop # CentOS/RHEL
mpstat
命令mpstat -P ALL 1
sysstat
包vmstat
命令vmstat 1
us
(用户空间)、sy
(系统空间)、id
(空闲)列显示CPU使用情况/proc/stat
文件cat /proc/stat
这个文件包含CPU活动的详细统计信息,可以编写脚本解析这些数据来计算CPU使用率。
sar
命令(系统活动报告)sar -u 1 3 # 每1秒采样一次,共3次
nmon
工具nmon
需要先安装:
sudo apt install nmon # Debian/Ubuntu
sudo yum install nmon # CentOS/RHEL
glances
工具glances
需要先安装:
pip install glances
以下是一个简单的bash脚本示例,用于计算CPU使用率:
#!/bin/bash
# 获取第一次CPU数据
read cpu user nice system idle iowait irq softirq steal guest guest_nice < <(cat /proc/stat | grep '^cpu ')
total1=$((user+nice+system+idle+iowait+irq+softirq+steal))
idle1=$idle
sleep 1
# 获取第二次CPU数据
read cpu user nice system idle iowait irq softirq steal guest guest_nice < <(cat /proc/stat | grep '^cpu ')
total2=$((user+nice+system+idle+iowait+irq+softirq+steal))
idle2=$idle
# 计算CPU使用率
total=$((total2-total1))
idle=$((idle2-idle1))
usage=$((100*(total-idle)/total))
echo "CPU使用率: $usage%"
对于桌面环境,还可以使用: - GNOME系统监视器 - KSysGuard (KDE) - Conky (桌面小工具)
选择哪种方法取决于你的具体需求,是实时监控还是长期记录,是否需要图形界面等。