Skip to content

Instantly share code, notes, and snippets.

@aprell
Last active May 13, 2018 09:41
Show Gist options
  • Select an option

  • Save aprell/58e2ec4b7e8dd9d408555aeebab77226 to your computer and use it in GitHub Desktop.

Select an option

Save aprell/58e2ec4b7e8dd9d408555aeebab77226 to your computer and use it in GitHub Desktop.
A poor man's profiler
#!/bin/bash
# A poor man's profiler
# Code adapted from https://poormansprofiler.org
set -eu
if [ "$#" -ne 2 ]; then
echo "Usage: $0 <program> <nsamples>"
exit 0
fi
filter() {
# Collapse stack traces and arrange in order of decreasing occurrence
awk -f poormanstraces.awk | sort | uniq -c | sort -rn
}
# If pidof doesn't find a process ID for the given program name, it exits with
# status 1, causing this script to exit as well (set -e).
pid=$(pidof "$1")
nsamples=$2
sleeptime=0
logfile="${1}_${pid}.log"
for _ in $(seq 1 "$nsamples"); do
gdb -ex "thread apply all bt" -batch -p "$pid"
sleep $sleeptime
done | tee "$logfile" | filter
# Collapse stack traces collected with gdb
# Code adapted from https://poormansprofiler.org
# Begin with empty stack trace
BEGIN { s = "" }
# Every thread prints the previous thread's stack trace
/^Thread/ { if (s != "") { print s; s = "" } }
# Build up stack trace, starting with current frame
/^\#/ { if (s != "") { s = s " | " $4 } else { s = $4 } }
# Must not forget to print the last thread's stack trace
END { print s }
@aprell

aprell commented May 13, 2018

Copy link
Copy Markdown
Author

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