Different Loop Speeds...

Hey!!!

I submitted the code for the problem INTEST(EASY) using three different loops and I was surprised that all gave me different timings…So is this really happening or some rounding error…

  1. while ID-1417249 Time-5.52

  2. for ID-1417242 Time-5.75

  3. do while ID-1417315 Time-5.56

If it is really happening…Plz tell me the reason behind it…
Thanks…

for and while loops are roughly equivalent.

You should just chose the one that is more appropriate for you code i.e. the one that makes the code more readable.For example if your loop requires a dummy variable then a for loop maybe more appropriate.
the slight difference is compiler dependent.

1 Like

I guess ‘for’ loop is the fastest in comparison to ‘while’ and ‘do-while’…

I think, that such test is meaningless, next time you run same code you will get f.e. 5.58 for while and 5.57 for do while, what one run proves? Nothing.

3 Likes

For more “surprises”, you should run the same (any) code several times and record the time for each run. Each time you will get a different result. Deviation of few hundreds of milliseconds is quite common.

Time of execution of a program depends on many parameters - like degree of multi-programming and cache performance. And programs which require disk activity, can show even more variations. And to some extent even temperature can affect the execution time :wink:

So different execution times might not depend on type of loop. Thankfully, we just need to worry about asymptotic complexity and some time about faster I/O.

BTW to time entire process on Linux you can use -> “$ time ./a.out”

5 Likes

actually it doesn’t, as all these three statements are compiled the same way in every processor architecture (ECX = value, loop_body, DEC ECX, JNZ beginning). it’s mostly a matter of C code readability, as explained by @abhi231594.

2 Likes