Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix Command For Benchmarking Code Running K times

Suppose I have a code executed in Unix this way:

$ ./mycode

My question is is there a way I can time the running time of my code executed K times. The value of K = 1000 for example.

I am aware of Unix "time" command, but that only executed 1 instance.

like image 541
neversaint Avatar asked Feb 18 '09 07:02

neversaint


4 Answers

to improve/clarify on Charlie's answer:

time (for i in $(seq 10000); do ./mycode; done)
like image 164
Evan Teran Avatar answered Nov 12 '22 20:11

Evan Teran


try

$ time ( your commands )

write a loop to go in the parens to repeat your command as needed.

Update

Okay, we can solve the command line too long issue. This is bash syntax, if you're using another shell you may have to use expr(1).

$ time (
> while ((n++ < 100)); do echo "n = $n"; done
> )

real    0m0.001s
user    0m0.000s
sys     0m0.000s
like image 30
Charlie Martin Avatar answered Nov 12 '22 22:11

Charlie Martin


Just a word of advice: Make sure this "benchmark" comes close to your real usage of the executed program. If this is a short living process, there could be a significant overhead caused by the process creation alone. Don't assume that it's the same as implementing this as a loop within your program.

like image 5
paprika Avatar answered Nov 12 '22 20:11

paprika


To enhance a little bit some other responses, some of them (those based on seq) may cause a command line too long if you decide to test, say one million times. The following does not have this limitation

time ( a=0 ; while test $a -lt 10000 ; do echo $a ; a=`expr $a + 1` ; done)
like image 3
Diego Sevilla Avatar answered Nov 12 '22 21:11

Diego Sevilla