[英]Is there some command to output only the CPU and Memory usage on Linux?
我正在創建一個接收我的 PC 的 CPU 和 MEM 使用率 (%) 的數據庫(研究目的)。
因此,我需要輸出(到 .txt 文件)整個系統(Linux/Ubuntu 18.04)的 CPU 和內存(RAM)使用率(%)
問題是我使用以下命令獲取按進程分隔的 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 排序的(我猜是“使用最多的進程”),但我只找到了這種方法來收集這些數據。
重點是:
是否有命令可以在沒有所有這些行的情況下收集 CPU 和 MEM 使用率(以 % 為單位)? 我只需要在數據庫中使用的百分比(數字)以及系統的結果使用情況,如下所示:
%CPU %MEM wed jan 9 11:26:39 -03 2019
53.0 32.2
您可以將腳本中的tail
命令替換為:
awk 'BEGIN {cpu=0;mem=0} {cpu+=$1; mem+=$2} 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+=$1; mem+=$2} 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 和內存使用情況。 我創建了下面的腳本。 我希望它會很有用
檢查資源文件
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.