Skip to content

Instantly share code, notes, and snippets.

@mjf
Last active August 29, 2015 13:57
Show Gist options
  • Save mjf/9384397 to your computer and use it in GitHub Desktop.
Save mjf/9384397 to your computer and use it in GitHub Desktop.
procmemstat - Show total and average memory usage of processes
#! /bin/sh
# procmemstat - Show total and average memory usage of processes
# Copyright (C) 2012 Matous J. Fialka, <http://mjf.cz/>
# Released under the terms of The MIT License
# Note: This is just a quick dirty hack...
#
# Check and parse arguments
#
if [ $# -lt 1 ]
then
printf -- 'Usage: procmemstat [procname1 procname2 .. procnameN]\n'
exit 0
fi
#
# Print header
#
printf -- ' %-14s\t % 7s\t % 7s\t%-32s\n' PROCESS TOTAL AVERAGE REMARK
#
# For every given process do print memory total and average usage
#
for _PROCESS in $@
do
ps -ylC "$_PROCESS" |
awk -vPROCESS="$_PROCESS" '
{
x += $8
y += 1
}
END {
z = 0
if((y - 1) < 1) {
y = 2
z = 1
}
printf "%-15s\t%7.1fM\t%7.1fM", PROCESS, x/1024, x/((y-1)*1024)
if(z)
printf "\tno such process"
printf "\n"
}
'
done |
#
# Print summary
#
awk '
{
print
sub(/M$/, nil, $2)
sub(/M$/, nil, $3)
x += $2
y += $3
}
END {
printf "\n\t\t%7.1fM\t%7.1fM\tTOTAL\n", x, y
}
'
@mjf
Copy link
Author

mjf commented Mar 6, 2014

Use it as follows:

$ procmemstat apache2 mysqld postgres postfix
 PROCESS           TOTAL         AVERAGE        REMARK                          
apache2          3386.9M           49.8M
mysqld            704.1M          704.1M
postgres           14.9M            3.0M
postfix             0.0M            0.0M        no such process

                 4105.9M          756.9M        TOTAL

Very useful when calculating Apache2 performance tunning parameters.

Note 1: To get rid of the header line, use:

$ procmemstat apache2 mysqld postgres postfix | sed 1d

Note 2: To get rid of the total line, use:

$ procmemstat apache2 mysqld postgres postfix | head -n -2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment