I’ve been doing some performance testing, and wanted a quick way to test how well or poorly changes affect a site. Normally I’d whip out the ol’ calculator app and do this manually. That got tiring after a while, so instead with the help of ChatGPT, I made this little bash script that will do the work for you:
#!/bin/bash
# Function to calculate the average of a list of numbers
average() {
local sum=0
local count=0
for num in "$@"; do
sum=$(echo "$sum + $num" | bc -l)
count=$((count+1))
done
echo "$sum / $count" | bc -l
}
# Parse arguments
for i in "$@"; do
case $i in
--before=*)
BEFORE="${i#*=}"
shift
;;
--after=*)
AFTER="${i#*=}"
shift
;;
*)
# unknown option
;;
esac
done
# Check if both BEFORE and AFTER parameters are provided
if [ -z "$BEFORE" ] || [ -z "$AFTER" ]; then
echo "Error: Missing required parameters."
echo "Usage: $0 --before=<comma-separated-values> --after=<comma-separated-values>"
exit 1
fi
IFS=',' read -ra BEFORE_LIST <<< "$BEFORE"
IFS=',' read -ra AFTER_LIST <<< "$AFTER"
# Calculate average for before and after lists
BEFORE_AVG=$(printf "%.2f\n" $(average "${BEFORE_LIST[@]}"))
AFTER_AVG=$(printf "%.2f\n" $(average "${AFTER_LIST[@]}"))
echo "Before average: $BEFORE_AVG"
echo "After average: $AFTER_AVG"
# Calculate average percent increase, decrease or no change for the list
if [ "$BEFORE_AVG" != "0.00" ]; then
PERCENT_CHANGE=$(echo "(($AFTER_AVG - $BEFORE_AVG) / $BEFORE_AVG) * 100" | bc -l)
if [ "$(echo "$PERCENT_CHANGE > 0" | bc -l)" -eq 1 ]; then
printf "Average percent increased: %.2f%%\n" "$PERCENT_CHANGE"
elif [ "$(echo "$PERCENT_CHANGE < 0" | bc -l)" -eq 1 ]; then
printf "Average percent decreased: %.2f%%\n" "$PERCENT_CHANGE" | tr -d '-'
else
echo "No change in average."
fi
else
echo "Percent change from before to after: undefined (division by zero)"
fi
Code language: Bash (bash)
It runs like this:
$ average.sh --before=13.07,9.75,16.14,7.71,10.32 --after=1.22,1.28,1.13,1.19,1.26
Before average: 11.40
After average: 1.22
Average percent decreased: 89.30%
In this instance, it was calculating seconds–but you need to remember that it only goes to two decimal places, so if you need something finer you’ll need to adjust the code or your inputs.
Happy Slacking!
Leave a Reply