简体   繁体   中英

Why one sample of code take more time to execute than other?

sample 1

for(int i = 0 ; i <= 99 ; i++)
    printf("Hello world");

sample 2

printf("Hello world"); // 1st print
printf("Hello world"); // 2nd print
.
.
.
printf("Hello world"); // 100th print

I know that sample one takes more time to execute than sample 2 and sample 2 takes more memory in text segment.

But, I want to know that what's going on behind the scene.

Imagine sample one being written as this sequence of operations:

i = 0
if (i <= 99)
print
i++
jump
if (i <= 99)
print
i++
jump
if (i <= 99)
print
i++
jump
...

While the second sample is simply:

print
print
print
print
...

This is extremely simplified, but you should get the idea - the first sample executes many more instructions to go through the loop.

As a side note - this is one of the optimizations the compiler will frequently do - it will unroll the loop and compile it as if there was no loop. To do that, it has to come to the conclusion it is worth while - note that sample two will compile into much greater total number of instructions and will take much more space in memory (and therefore will take longer to load).

The code at sample 2 can be quicker if programmed properly.

As you have described, there are 100 calls to printf("... "); with the same string as parameter. If the compiler is an optimizing compiler, it can detect you are passing exactly the same parameter and don't pop the pointer after the call, so it won't need to push it again for the next call.

Also, the difference in speed between the loop is the time spent in jumping back to the beginning of the loop. With present architectures, that can be even an advantage, as the whole loop code is cached by the CPU (this cannot be done with a large set of similar calls) and no memory access is to be made to get the instructions loaded, compensating for the time spent in executing the loop instructions.

But... even, with a good optimizing compiler, it can detect you have put the same sentence 100 times and fold'em in a loop, with a hidden control variable (as in sample 1) so you don't se a difference in time on execution.

Optimizing compilers are used to detect these kind of constructions and to change the code to be more efficient.

A good reference for this kind of material is this: http://en.wikipedia.org/wiki/Compilers:_Principles,_Techniques,_and_Tools

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM