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


当前回答

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

其他回答

根据@Neon的回答,我的观点是:

pidstat -h -r -u -v -p $(ps aux | grep <process name> | awk '{print $2}' | tr '\n' ',')

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

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

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

使用pidstat(来自sysstat -参考链接)。

例如,每5秒监控这两个进程id(12345和11223)的使用情况

$ pidstat -h -r -u -v -p 12345,11223 5

下面的命令获取特定进程(pid)每40秒CPU和内存使用率的平均值

pidstat 40 -ru -p <pid>

我的案例的输出(前两行为CPU使用率,后两行为内存):

02:15:07 PM       PID    %usr %system  %guest    %CPU   CPU  Command
02:15:47 PM     24563    0.65    0.07    0.00    0.73     3  java

02:15:07 PM       PID  minflt/s  majflt/s     VSZ    RSS   %MEM  Command
02:15:47 PM     24563      6.95      0.00 13047972 2123268   6.52  java

根据@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