20

I have this command:

time -p sh -c 'command1; command2;'

So command1and command2 is executed and I get the real, user and sys time printed on the console.

But I want that command1; command2; is looped 10 times and then I want to get the time which is used for the two commands.

3 Answers 3

25

With zsh:

time (repeat 10 {cmd1; cmd2})

zsh's repeat is inherited from csh.

With tcsh:

time repeat 10 eval 'cmd1; cmd2'

Would give you the time for each iteration and the overall time at the end.

20

You can write a simple for-loop

 time -p bash -c "for (( i=0; i<10; i++ )); do command1; command2; done;"

Note that I used bash instead of sh for the loop.

4
  • 24
    In bash you can just time (for i in {1..10}; do sleep 1 ; done) Mar 24, 2013 at 18:47
  • 2
    @frostschutz: Yours seems like a much better answer. Please post it as an answer.
    – Chris Page
    Jan 24, 2016 at 21:58
  • anyway to do this for multiline forloop? Dec 10, 2020 at 15:14
  • @frostschutz's answer works for a multiline for loop too. Just time ( <multiline loop> )
    – daviewales
    Feb 28, 2023 at 4:53
6

For simple for loops you can time the for loop directly:

time for i in {1..10}; do echo $i; sleep 1; done
2
  • This doesn't print the time for me...
    – user5601
    Jul 15, 2022 at 0:36
  • user5601: using zsh? with zsh the for has to be in a subshell: time (for i in {1..10}; do echo $i; sleep 1; done)
    – JohnLittle
    May 8, 2023 at 22:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .