Skip to content

Instantly share code, notes, and snippets.

@rishid
Last active February 12, 2024 20:24
Show Gist options
  • Save rishid/7793425943dd3f9721d1bdfc2676668d to your computer and use it in GitHub Desktop.
Save rishid/7793425943dd3f9721d1bdfc2676668d to your computer and use it in GitHub Desktop.
Time a command for N iterations and print out the average real/user/sys time used
#!/bin/bash
if [ "$#" -ne 2 ]; then
echo "Usage: $0 <command> <repeat>"
exit 1
fi
command="$1"
repeat="$2"
real_sum=0
user_sum=0
sys_sum=0
for ((i=0; i<repeat; i++)); do
echo "Executing repetition $((i+1))..."
#result=$(/usr/bin/time -p $command 2>&1)
result=$({ time -p $command > /dev/null 2>&1 ; } 2>&1)
real_time=$(echo "$result" | grep real | awk '{print $2}')
user_time=$(echo "$result" | grep user | awk '{print $2}')
sys_time=$(echo "$result" | grep sys | awk '{print $2}')
echo $real_time " " $user_time " " $sys_time
real_sum=$(echo "$real_sum + $real_time" | bc)
user_sum=$(echo "$user_sum + $user_time" | bc)
sys_sum=$(echo "$sys_sum + $sys_time" | bc)
done
average_real=$(echo "scale=2; $real_sum / $repeat" | bc)
average_user=$(echo "scale=2; $user_sum / $repeat" | bc)
average_sys=$(echo "scale=2; $sys_sum / $repeat" | bc)
echo "Average Real Time: $average_real seconds"
echo "Average User Time: $average_user seconds"
echo "Average Sys Time: $average_sys seconds"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment