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


当前回答

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

其他回答

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

对于那些纠结了一段时间,想知道为什么选定的答案不管用的人:

ps -p <pid> -o %cpu,%mem

%cpu和%mem之间没有空格。

根据@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
ps -p <pid> -o %cpu,%mem,cmd

(您可以省略“cmd”,但这可能有助于调试)。

注意,这给出了进程在运行期间的平均CPU使用率。

上面列出了消耗cpu和内存最多的进程

        ps axo %cpu,%mem,command | sort -nr | head