Monday 15 July 2013

c++ - Loop with a zero execution time -



c++ - Loop with a zero execution time -

is possible have loop has 0 execution time? think empty loop should have execution time since there overhead associated it.

yes, under as-if rule compiler obligated emulate observable behavior of code, if have loop not have observable behavior can optimized away , hence have 0 execution time.

examples

for illustration next code:

int main() { int j = 0 ; for( int = 0; < 10000; ++i ) { ++j ; } }

compiled gcc 4.9 using -o3 flag ends reducing next (see live):

main: xorl %eax, %eax # ret

pretty much optimizations allowed fall under as-if rule, exception aware of copy elison allowed effect observable behavior.

some other examples include dead code elimination can remove code compiler can prove never executed. illustration though next loop indeed contain side effect can optimized out since can prove never executed (see live):

#include <stdio.h> int main() { int j = 0 ; if( false ) // loop never execute { for( int = 0; < 10000; ++i ) { printf( "%d\n", j ) ; ++j ; } } }

the loop optimize away same previous example. more interesting illustration case calculation in loop can deduced constant thereby avoiding need loop(not sure optimization category falls under), example:

int j = 0 ; for( int = 0; < 10000; ++i ) { ++j ; } printf( "%d\n", j ) ;

can optimized away (see live):

movl $10000, %esi #, movl $.lc0, %edi #, xorl %eax, %eax # phone call printf #

we can see there no loop involved.

where as-if rule covered in standard

the as-if rule covered in draft c99 standard section 5.1.2.3 program execution says:

in abstract machine, expressions evaluated specified semantics. actual implementation need not evaluate part of look if can deduce value not used , no needed side effects produced (including caused calling function or accessing volatile object).

the as-if rule applies c++, gcc produce same result in c++ mode well. c++ draft standard covers in section 1.9 program execution:

the semantic descriptions in international standard define parameterized nondeterministic abstract machine. international standard places no requirement on construction of conforming implementations. in particular, need not re-create or emulate construction of abstract machine. rather, conforming implementations required emulate (only) observable behavior of abstract machine explained below.5

c++ c optimization execution-time as-if

No comments:

Post a Comment