我想知道Linux上单个进程的CPU和内存使用情况——我知道PID。希望我每秒钟都能得到它,并使用'watch'命令将其写入CSV。我可以使用什么命令从Linux命令行中获得这些信息?


当前回答

ps aux|awk  '{print $2,$3,$4}'|grep PID

其中第一列是PID,第二列是CPU使用率,第三列是内存使用率。

其他回答

你可以使用top -b和grep输出你想要的pid(带-b标志的top在批处理模式下运行),或者也可以使用-p标志并指定pid而不使用grep。

ps axo pid,etime,%cpu,%mem,cmd | grep 'processname' | grep -v grep

PID -进程号

etime -进程运行/活时长

%cpu - cpu使用率

%mem -内存使用率

cmd -命令

将processname替换为任何你想跟踪的进程,mysql nginx php-fpm等等…

根据@caf的回答,这对我来说很有效。

计算给定PID的平均值:

measure.sh

times=100
total=0
for i in $(seq 1 $times)
do
   OUTPUT=$(top -b -n 1 -d 0.1 -p $1 | tail -1 | awk '{print $9}')
   echo -n "$i time: ${OUTPUT}"\\r
   total=`echo "$total + $OUTPUT" | bc -l`
done
#echo "Average: $total / $times" | bc

average=`echo "scale=2; $total / $times" | bc`
echo "Average: $average"

用法:

# send PID as argument
sh measure.sh 3282

caf的答案是: Top -p <pid>

这将自动刷新CPU使用情况,因此非常适合监控。

ps aux | awk '{print $4"\t"$11}' | sort | uniq -c | awk '{print $2" "$1" "$3}' | sort -nr

或者每个进程

ps aux | awk '{print $4"\t"$11}' | sort | uniq -c | awk '{print $2" "$1" "$3}' | sort -nr |grep mysql