aboutsummaryrefslogtreecommitdiff
path: root/tests/helpers/profiler.bash
diff options
context:
space:
mode:
authorAlexander M Pickering <alex@cogarr.net>2026-07-21 20:19:46 -0500
committerAlexander M Pickering <alex@cogarr.net>2026-07-21 20:19:46 -0500
commit657fb0007f39f07cc0401e0c5d03e25df6234aa4 (patch)
treef73fe23232dc80802f39caed738c38464a60ec6d /tests/helpers/profiler.bash
downloadtrbldoc-657fb0007f39f07cc0401e0c5d03e25df6234aa4.tar.gz
trbldoc-657fb0007f39f07cc0401e0c5d03e25df6234aa4.tar.bz2
trbldoc-657fb0007f39f07cc0401e0c5d03e25df6234aa4.zip
Inital commit.
Diffstat (limited to 'tests/helpers/profiler.bash')
-rw-r--r--tests/helpers/profiler.bash53
1 files changed, 53 insertions, 0 deletions
diff --git a/tests/helpers/profiler.bash b/tests/helpers/profiler.bash
new file mode 100644
index 0000000..c3d5207
--- /dev/null
+++ b/tests/helpers/profiler.bash
@@ -0,0 +1,53 @@
+# Profiler implementation
+profile() {
+ # Set default options
+ local file=profiler.log
+
+ # Open a file descriptor for writing to $file and save it in $tracefd
+ exec {tracefd}>"$file"
+ # Send trace output to $tracefd
+ export BASH_XTRACEFD="$tracefd"
+ # Print microsecond time in trace output
+ export PS4='+ $EPOCHREALTIME '
+ # Enable tracing, run script, and disable tracing
+ set -x
+ bash -x -- "$@"
+ set +x
+ # Un-redirect the trace output. This also closes the file descriptor.
+ unset BASH_XTRACEFD
+ export -n BASH_XTRACEFD PS4
+
+ # Remove "source" line from output and change last line to only include the
+ # timestamp with no name.
+ sed -i -e 1d -e '$s/\(+\+ [0-9\.]\+\) .*$/\1/' "$file"
+}
+
+analyze() {
+ # Set defaults
+ local file=profiler.log
+ local -a sortcmd=(cat) tablecmd=(cat)
+
+ # Declare variables
+ local timestamp nestlvl cmd next_timestamp next_nestlvl next_cmd duration
+ # Open file as a file descriptor so we can re-use the same stream
+ exec {fd}<"$file";
+ # Read first line
+ read -r nestlvl timestamp cmd <&"$fd"
+ # Process each line
+ while read -r next_nestlvl next_timestamp next_cmd
+ do
+ duration="$(echo "scale=6; $next_timestamp" - "$timestamp" | bc)"
+ # Prepend leading zero
+ if [ "${duration:0:1}" = . ]
+ then
+ duration="0$duration"
+ fi
+ echo "$duration" "$nestlvl" "$cmd"
+
+ timestamp="$next_timestamp"
+ nestlvl="$next_nestlvl"
+ cmd="$next_cmd"
+ done <&"$fd" | "${sortcmd[@]}" | "${tablecmd[@]}"
+ # Close file descriptor
+ exec {fd}<&-
+}