19

I want to measure the running time of some SQL query in postgresql. Using BASH built-in time, I could do the following:

$ time (echo "SELECT * FROM sometable" | psql)

I like GNU time, which provides more formats. However I don't know how to do it with pipe line. For simplicity, I use ls | wc in the following examples:

$ /usr/bin/time -f "%es" (ls | wc)                                                      
-bash: syntax error near unexpected token `('

$ /usr/bin/time -f "%es" "ls | wc"                                                  
/usr/bin/time: cannot run ls | wc: No such file or directory

If I do not group the pipe in any way, it does not complains:

$ /usr/bin/time -f "%es" ls | wc       
0.00s

But apparently, this only measure the first part of the pipe, as showing in the next example

$ /usr/bin/time -f "%es" ls | sleep 20                                                  
0.00s 

So the question is what is the correct syntax for GNU Time with pipe line?

stderr
  • 1,038
  • 1
  • 11
  • 18

2 Answers2

18

Call the shell from time:

/usr/bin/time -f "%es" bash -c "ls | wc"

Of course, this will include the shell start-up time as well; it shouldn't be too much, but if you're on a system that has a lightweight shell like dash (and it's sufficient to do what you need), then you could use that to minimize the start-up time overhead:

/usr/bin/time -f "%es" dash -c "ls | wc"

Another option would be to just time the command you are actually interested in, which is the psql command. time will pass its standard input to the program being executed, so you can run it on just one component of the pipeline:

echo "SELECT * FROM sometable" | /usr/bin/time -f "%es" psql
Brian Campbell
  • 322,767
  • 57
  • 360
  • 340
3

Create a script that calls your pipeline. Then

/usr/bin/time -f '%es' script.sh
choroba
  • 231,213
  • 25
  • 204
  • 289