Skip to content

Instantly share code, notes, and snippets.

@rrmesquita
Created February 23, 2024 23:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rrmesquita/9dc25d6b85830bdaaa5b356e70d3b642 to your computer and use it in GitHub Desktop.
Save rrmesquita/9dc25d6b85830bdaaa5b356e70d3b642 to your computer and use it in GitHub Desktop.
Average response time
#!/usr/bin/env bash
# calculate the average response time of the server for a given url received as an argument.
# Number of requests to make
requests=$1
# URL to make requests to
url=$2
# Array to store the process IDs of the background processes
pid_array=()
# Whether to run requests in parallel or not
parallel=true
# Timeout between requests
timeout=0.2
if [ -z "$requests" ] || [ -z "$url" ]; then
echo "Usage: $0 <number of requests> <url>"
exit 1
fi
# Temporary file to store response times
tmpfile=$(mktemp)
# make a single request and output response time
request_and_calculate_time() {
local url=$1
local response_time=$(curl -s -w "%{time_total}" -o /dev/null "$url")
echo "$response_time" >>"$tmpfile"
time_in_ms "$response_time"
}
time_in_ms() {
echo "$(echo "scale=3; $1 * 1000" | bc) ms"
}
# Iterate through the number of requests and run them
for i in $(seq 1 $requests); do
if [ "$parallel" = true ]; then
request_and_calculate_time "$url" &
else
request_and_calculate_time "$url"
fi
sleep "$timeout"
pid_array+=($!) # Store the process IDs in an array
done
# Wait for all background processes to finish
for pid in "${pid_array[@]}"; do
wait $pid
done
# Calculate the average response time
average_time=$(awk '{ total += $1 } END { print total / NR }' "$tmpfile")
# Clean up temporary file
rm "$tmpfile"
# Display the average response time
echo "Average response time: $(time_in_ms $average_time)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment