memusg 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. rm -f "histogram.mem.usg"
  27. # monitor the memory usage in the background.
  28. (
  29. peak=0
  30. while sizes=`sizes $pgid`
  31. do
  32. set -- $sizes
  33. sample=$((${@/#/+}))
  34. echo "$sample" >> "histogram.mem.usg"
  35. let peak="sample > peak ? sample : peak"
  36. sleep 0.1
  37. done
  38. echo "memusg \`$command\`: peak=$peak kiloBytes" >> "peak.mem.usg"
  39. ) &
  40. monpid=$!
  41. echo "running: exec $@"
  42. # run the given command
  43. exec "$@"