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)
{
r++;
}
}
}
}
This code executes on i3Core in 0.000001 wall seconds, checked with boost::timer::auto_cpu_timer on i7Core.
But with visual studio 2010 it seems to run in infinite time.
What is wrong with GCC or VS ? Is GCC optimizing too much?
Yes, GCC is 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
rout at the end: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 out an unused variable incremented inside a loop?