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


当前回答

根据@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 -C chrome -o %cpu,%mem,cmd

-C选项允许你在不知道pid的情况下使用进程名。

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

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

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

我用htop

sudo apt install htop
htop

按F3查找感兴趣的进程,记住PID。用q退出并再次启动htop,只显示您想要的进程

htop -p $PID

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

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

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

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

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