2

I need to execute a curl command inside a for loop multiple times, and get the average time it took to execute a single curl. This is what I have:

while read query; do
  TIMEFORMAT=%R; time for i in {1..3}; do curl -s -w '\n' -XPOST -H 'Content-Type: application/x-www-form-urlencoded' --data-urlencode query='${query}' ${nginx_url} > /dev/null; done
done < queries.txt

This prints the number of seconds in stdout, but I need to assign that number to a variable to divide it by 3 in order to get the average.

I have tested with:

realtime=$(time -f "%E" for i in {1..3} ..etc..)
realtime=`time -f "%E" for i in {1..3} ..etc..`

But this gives syntax error ./test-suite.sh: line 23: syntax error near unexpected tokendo'.

I have also tested with:

realtime=$(bash -c "TIMEFORMAT=%R; time for i in {1..3} ..etc..")
realtime=$(bash -c "time -f "%E" for i in {1..3} ..etc..")
realtime=$(bash -c "TIMEFORMAT=%R; time for i in {1..3} do ..etc.. ; done; echo $realtime")

All of them bear no results. Any ideas are welcome.

2
  • You aren't using /usr/bin/time. You're using bash's time keyword. Commented Aug 7, 2017 at 23:16
  • Had the same issues with /usr/bin/time, forgot to add that,but thx! Commented Aug 11, 2017 at 9:08

2 Answers 2

1

My suggestion would be (slightly modified, since I don't have your curl/HTTP setup):

$ t=$(TIMEFORMAT=%R bash -c 'time for i in {1..3}; do sleep $((RANDOM % 5)); done' 2>&1)
$ avg=$(bc <<< "scale=3; $t/3")
$ echo $avg # YMMV
2.667

Since time is a bash built-in, we need to place the stderr redirection "outside" of the time call; that's why I wrapped the main part with bash -c ....

You don't need to set TIMEFORMAT every time through the loop; just put it in the environment for the call to bash/time.

Note that shell arithmetic is integer-based, so for floating-point values, use something like bc. My time output had 3 decimal places, so that's what I asked bc for as well.

0

I got it, I have to enclose the command into parenthesis as well,

mytime=$(time (for i in {1..3}; do curl -s -w '\n' -XPOST -H 'Content-Type: application/x-www-form-urlencoded' --data-urlencode query='select distinct ?Concept where {[] a ?Concept} LIMIT 100' http://143.233.226.61:443/sparql > /dev/null; done) 2>&1 1>/dev/null)

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.