memusg 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #!/usr/bin/env bash
  2. # memusg -- Measure memory usage of processes
  3. # Usage: memusg COMMAND [ARGS]...
  4. #
  5. # Author: Jaeho Shin <netj@sparcs.org>
  6. # Created: 2010-08-16
  7. set -um
  8. # check input
  9. [ $# -gt 0 ] || { sed -n '2,/^#$/ s/^# //p' <"$0"; exit 1; }
  10. # TODO support more options: peak, footprint, sampling rate, etc.
  11. pgid=`ps -o pgid= $$`
  12. command="$@"
  13. # make sure we're in a separate process group
  14. if [ $pgid = $(ps -o pgid= $(ps -o ppid= $$)) ]; then
  15. cmd=
  16. set -- "$0" "$@"
  17. for a; do cmd+="'${a//"'"/"'\\''"}' "; done
  18. exec bash -i -c "$cmd"
  19. fi
  20. # detect operating system and prepare measurement
  21. case `uname` in
  22. Darwin|*BSD) sizes() { /bin/ps -o rss= -g $1; } ;;
  23. Linux) sizes() { /bin/ps -o rss= -$1; } ;;
  24. *) echo "`uname`: unsupported operating system" >&2; exit 2 ;;
  25. esac
  26. # monitor the memory usage in the background.
  27. (
  28. peak=0
  29. while sizes=`sizes $pgid`
  30. do
  31. set -- $sizes
  32. sample=$((${@/#/+}))
  33. let peak="sample > peak ? sample : peak"
  34. sleep 0.1
  35. done
  36. echo "memusg \`$command\`: peak=$peak kiloBytes" >> "peak.mem.usg"
  37. ) &
  38. monpid=$!
  39. echo "running: exec $@"
  40. # run the given command
  41. exec "$@"