Skip to content

Instantly share code, notes, and snippets.

@solidsnack
Forked from netj/memusg
Last active December 17, 2015 12:39
Show Gist options
  • Save solidsnack/5611887 to your computer and use it in GitHub Desktop.
Save solidsnack/5611887 to your computer and use it in GitHub Desktop.
Clean up variable declarations.
#!/bin/bash
set -o errexit -o nounset -o pipefail
function -h {
cat <<USAGE
USAGE: memusg COMMAND [ARGS]
Measure memory usage of processes.
This script is inspired by a script of the same name written by Jaeho Shin
<netj@sparcs.org>.
Only tested on OS X.
USAGE
}; function --help { -h ;}
function memusg {
local pgid mem mems=()
if [[ $# = 1 && $1 =~ ^[0-9]+$ ]]
then pgid="$1"
else bash -i -c '$@' "$1" "$@" & pgid="$!"
fi
while sleep 0.1
do
mem="$(psg "$pgid" -o rss= | xargs | tr ' ' + | bc)" || break
mems=( "${mems[@]:+${mems[@]}}" "$mem" )
done
wait
[[ ${#mems[@]} -le 0 ]] || percentiles "${mems[@]}" >&2
}
uname="$(uname)"
function psg {
local pgid="$1" ; shift
case "$uname" in
Darwin|*BSD) ps -g "$pgid" "$@" ;;
Linux) ps -"$pgid" "$@" ;;
*) err "Your OS is not supported." ;;
esac
}
function percentiles {
local unscaled i j data=()
data=( $(printf '%s\n' "$@" | sort -n ) )
printf '%s\t%s\n' %-tile K-mem
for percentile in 100 99 95 90 50
do
unscaled=$(( $percentile * ($# - 1) ))
i=$(( $unscaled / 100 ))
j=$(( ($unscaled + 99) / 100 ))
i="${data[$i]}"
j="${data[$j]}"
printf '%d\t%d\n' "$percentile" $(( ($i + $j) / 2 ))
done
}
function msg { out "$*" >&2 ;}
function err { local x=$? ; msg "$*" ; return $(( $x == 0 ? 1 : $x )) ;}
function out { printf '%s\n' "$*" ;}
if [[ ${1:-} ]] && declare -F | cut -d' ' -f3 | fgrep -qx -- "${1:-}"
then "$@"
else memusg "$@"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment