是否有一些命令只输出 CPU 和 Linux 上的内存使用情况?

Is there some command to output only the CPU and Memory usage on Linux?

我正在创建一个数据库(研究目的)来接收我的 PC CPU 和 MEM 使用率 (%)。

因此,我需要输出(到 .txt 文件)CPU 和我整个系统的内存 (RAM) 使用率 (%) (Linux/Ubuntu 18.04)

问题是我使用以下命令获取按进程分隔的 CPU 和 MEM 信息:

>> while true; do (echo "%CPU %MEM $(date)" && ps -e -o pcpu,pmem --sort=pcpu | cut -d" " -f1-5 | tail) > test.txt; sleep 5; done

给出以下输出:

%CPU %MEM wed jan  9 11:26:39 -03 2019
 0.0  0.0
 0.1  0.2
 0.1  1.4
 0.1  1.6
 0.4  1.4
 0.6  2.8
 1.0  2.4
 1.5  6.1
 4.1  0.6
12.4  8.2

我知道此命令按 pcpu 排序(我猜是最多 "in-use processes"),但我只找到这种方式来收集这些数据。

重点是:

是否有一个命令可以收集 CPU 和 MEM 使用情况(以 % 为单位)而不需要所有这些行?我只需要在数据库中使用的百分比(数字)以及系统的结果使用情况,如下所示:

%CPU %MEM wed jan  9 11:26:39 -03 2019
 53.0 32.2

您可以将脚本中的 tail 命令替换为:

awk 'BEGIN {cpu=0;mem=0} {cpu+=; mem+=} END {print cpu,mem}'

你的行会变成:

while true; do (echo "%CPU %MEM $(date)" && ps -e -o pcpu,pmem --sort=pcpu | cut -d" " -f1-5 | awk 'BEGIN {cpu=0;mem=0} {cpu+=; mem+=} END {print cpu,mem}') > test.txt; sleep 5; done

不是很优雅或高效,但这是使用 Python 和 psutil 库的替代解决方案...

打印 cpu% 和 mem% 的简短 Python 程序如下所示:

import psutil

cpu = psutil.cpu_percent()
mem = psutil.virtual_memory().percent
print("{}% {}%".format(cpu, mem))

可以这样写 shell 一行:

$ python3 -c 'import psutil; cpu=psutil.cpu_percent(); mem=psutil.virtual_memory().percent; print("{}% {}%".format(cpu, mem))'

所以你可以在你的shell循环中运行它,像这样:

$ while true; do python3 -c 'import psutil; cpu=psutil.cpu_percent(); mem=psutil.virtual_memory().percent; print("{}% {}%".format(cpu, mem))'; sleep 5; done

(注意:psutil 可以安装在您的 Ubuntu 系统上:$ sudo apt install python3-psutil

我有类似的要求,只打印 CPU 和内存使用情况。我创建了以下脚本。希望有用

checkResources.sh

CPU=$(top -b -d1 -n1|grep -i 'Cpu(s)'|head -c21 |cut -d ' ' -f2)
usedmem=$(top -b -d1 -n1|grep -i 'used'|head -c55 | cut -d ' ' -f10)
totmem=$(top -b -d1 -n1|grep -i 'used'|head -c19 |  cut -d ' ' -f4)
echo "CPU = $CPU%"
echo "Memory = $((usedmem/1024))/$((totmem/1024)) MB"

这将打印输出如下

CPU = 97.0%

内存 = 10230/15867 MB