Release mode that skips parts of the code

When I tried to check the speed of the execution of functions, I found that not all parts of my code work in Release mode. However, the same code works fine in Debug mode.

I am using a VC ++ compiler with /O2 optimization.

Here is cut out the part that does not work.

 int main() { boost::timer::auto_cpu_timer t; for(int i = 0; i < 1000000; i++) gcdb(i, 5); return 0; } 

Generated assembly in release mode, the code for the for loop is absent only in this mode.

 int main() { 000000013F8E1280 sub rsp,88h 000000013F8E1287 mov rax,qword ptr [__security_cookie (013F8E7150h)] 000000013F8E128E xor rax,rsp 000000013F8E1291 mov qword ptr [rsp+70h],rax boost::timer::auto_cpu_timer t; 000000013F8E1296 lea rcx,[t] 000000013F8E129B mov edx,6 000000013F8E12A0 call boost::timer::auto_cpu_timer::auto_cpu_timer (013F8E2DA0h) for(int i = 0; i < 1000000; i++) gcdb(i, 5); return 0; 000000013F8E12A5 lea rcx,[t] 000000013F8E12AA call boost::timer::auto_cpu_timer::~auto_cpu_timer (013F8E2810h) 000000013F8E12AF xor eax,eax } 

gcdb() is just a function to find the GCD of two numbers.

What could be the reason for skipping this code?

+4
source share
2 answers

What you see here is compiler optimization, known as Dead Code Elimination .

When the compiler sees that the result of some code is not needed, it can be eliminated. This is the standard optimization used by all modern compilers.

A workaround for the compiler to not be able to optimize it is to actually use the output:

 int main() { boost::timer::auto_cpu_timer t; int sum = 0; for(int i = 0; i < 1000000; i++) sum += gcdb(i, 5); cout << sum << endl; return 0; } 

Related: How does GCC optimize an unused variable increasing inside a loop?

+8
source

If the compiler can prove that there are no side effects, and you are not using the result anywhere, it can completely trim this loop.

Try to summarize the results, and then return the whole amount from the main one - in this way there is an observed side effect that the too optimistic optimizer should stop.

+2
source

Source: https://habr.com/ru/post/1393402/


All Articles