我想知道Linux上单个进程的CPU和内存使用情况——我知道PID。希望我每秒钟都能得到它,并使用'watch'命令将其写入CSV。我可以使用什么命令从Linux命令行中获得这些信息?
当前回答
ps aux|awk '{print $2,$3,$4}'|grep PID
其中第一列是PID,第二列是CPU使用率,第三列是内存使用率。
其他回答
根据这个答案,我们可以通过收集N个样本,采样周期为T来估计特定进程在特定时间内的平均CPU和内存利用率,如下所示:
N=3;
T=1;
PROCESS_NAME="my_proc";
top -b -c -n $(let tmp=N+1; echo $tmp) -d ${T} -p $(pgrep ${PROCESS_NAME}) |
grep ${PROCESS_NAME} |
tee /var/tmp/foo.log |
tail -n +2 |
awk -v N=$N 'BEGIN{
c=0;
m=0
}{
c=c+$9;
m=m+$10
}END{
printf("%s %s\n", c/N, m/N)
}';
为了能够计算结果,我们将top的输出收集到/var/tmp/foo.log文件中。预期输出是这样的:
2.33333 6.9
以及日志文件的内容:
196918 root 20 0 24.4g 1.3g 113872 S 0.0 6.9 39:58.15 my_proc
196918 root 20 0 24.4g 1.3g 113872 S 2.0 6.9 39:58.17 my_proc
196918 root 20 0 24.4g 1.3g 113872 S 3.0 6.9 39:58.20 my_proc
196918 root 20 0 24.4g 1.3g 113872 S 2.0 6.9 39:58.22 my_proc
注意,我们忽略了top命令的第一次执行(tail -n +2)。
上面列出了消耗cpu和内存最多的进程
ps axo %cpu,%mem,command | sort -nr | head
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
(如果你使用的是MacOS 10.10,试试top的cumulative -c选项:
top -c a -pid PID
(此选项在其他linux中不可用,尝试使用Scientific linux el6和RHEL6)
下面的命令获取特定进程(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