Answers:
这应该做您需要的。它从获取信息/proc/$PID/statm
并打印(从man procfs
):
size total program size
(same as VmSize in /proc/[pid]/status)
resident resident set size
(same as VmRSS in /proc/[pid]/status)
share shared pages (from shared mappings)
data data + stack
剧本:
#!/usr/bin/env bash
## Print header
echo -e "Size\tResid.\tShared\tData\t%"
while [ 1 ]; do
## Get the PID of the process name given as argument 1
pidno=`pgrep $1`
## If the process is running, print the memory usage
if [ -e /proc/$pidno/statm ]; then
## Get the memory info
m=`awk '{OFS="\t";print $1,$2,$3,$6}' /proc/$pidno/statm`
## Get the memory percentage
perc=`top -bd .10 -p $pidno -n 1 | grep $pidno | gawk '{print \$10}'`
## print the results
echo -e "$m\t$perc";
## If the process is not running
else
echo "$1 is not running";
fi
done
然后,您可以调用脚本,并为其指定一个进程名称。例如:
$ memusage.sh firefox
Size Resid. Shared Data %
517193 261902 9546 400715 12.8
517193 261902 9546 400715 12.8
517193 261902 9546 400715 12.8
517193 262100 9546 400715 12.8
517193 262100 9546 400715 12.8
517193 262100 9546 400715 12.8
517209 261899 9546 400731 12.8
517209 261899 9546 400731 12.8
笔记:
man
,不知道为什么您的编辑被拒绝了。
多年后,我发现valgrind(也)有一个用于此的工具:
# record memory usage
$ valgrind --tool=massif bash -c "sleep 5; echo hey";
==5281== Massif, a heap profiler
==5281== Copyright (C) 2003-2015, and GNU GPL'd, by Nicholas Nethercote
==5281== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==5281== Command: bash -c sleep\ 5;\ echo\ hey
==5281==
hey
==5281==
# print the usage (5281 was the pid of bash, your filename will be different)
$ ms_print massif.out.4682
注意:valgrind的作用不只是观察:它需要注入一些代码并获取内存快照。这可能会损害统计的准确性。
/proc/$PID/statm
),然后休眠100ms并重复执行。为什么你不能只是不断扔PID的相关statm
经过cat
,也许使用一些正则表达式来过滤掉多余/不需要的价值观,只是做了sleep 0.01
?某些操作系统不允许使用亚秒级的sleep
值,因此在这种情况下,您必须采用Python路由(而应使用Python的内置time
库进行睡眠)。