Take the 2-minute tour ×
long long r = 0;
long long k = 0;
for (; k < 9999999999999; k++) 
    for (long long i = 0; i < 9999999999999; i++) 
        for (long long j = 0; j < 9999999999999; j++) 
            r = (r + (i * j) % 100) % 47;
            if (r != 0) 

This code executes on i3Core in 0.000001 wall s. Checked with boost::timer::auto_cpu_timer. On i7Core But with visual studio 2010 it run in infinite time i guess =) What is wrong with gcc ot vs ?

share|improve this question
is r being ever used? It's probably discarded together with all loops. See assembly. If you want to ensure loop execution, print r –  Anycorn Mar 13 '12 at 6:48
Note, the term "super optimization" is typically used for compilers that generate all possible combinations of something and pick the most efficient one. –  Lindydancer Mar 13 '12 at 7:47
too bad it's not even super-formatting your code ;-) –  CAFxX Mar 13 '12 at 7:55
Sorry, didnt care about this test piece of code –  Denis Ermolin Mar 13 '12 at 8:07

1 Answer 1

up vote 13 down vote accepted

Yes, GCC is "super-optimizing" that code.

Specifically, it knows that you aren't using the result, so it's removing all of it.
(You're never using the variable r.)

This is called Dead Code Elimination.

To prevent the compiler from optimizing it out, you'll need to use the result somehow. Try printing r out at the end:

cout << r << endl;

However, I warn that you'll need to reduce the iteration counts, or it probably won't finish in your lifetime.

I just tested this in VS2010 x64. Looking at the assembly, it is clear that VS2010 is not able to optimize out the entire loop.

It goes to show that different compilers vary in their ability to optimize different things.

Related, and more in-depth: How does GCC optimize C code?

share|improve this answer
Visual Studio not being able to optimize this completely is actually a bit scary... I'll test with VS11 Beta and report back. –  Xeo Mar 13 '12 at 7:11
@edA-qamort-ora-y That would work, though it would also block the compiler from doing mem-to-register promotion - which would probably nuke performance. –  Mysticial Mar 13 '12 at 7:14
@Mystical, I just mean the final result -- yes, if used in the calculation you'd kill performance. Declare a global volatile long long junk; and then assign r to it junk = r;. –  edA-qa mort-ora-y Mar 13 '12 at 7:18
This is kinda depressing. Even after removing the outer two loops VS11 beta is not able to optimize the code out. –  Xeo Mar 13 '12 at 7:19
@Xeo Unless you're writing micro-benchmarks like this, it's very uncommon in actual code to have this much dead-code in such constructs. So I'd probably assume MS didn't find it worth it to implement the dependency analysis needed to prove that this loop is useless. –  Mysticial Mar 13 '12 at 7:22

Your Answer


