Compiler optimization causing the performance to slow down

Posted by aJ on Stack Overflow See other posts from Stack Overflow or by aJ
Published on 2010-04-29T06:41:22Z Indexed on 2010/04/29 6:47 UTC
Read the original article Hit count: 457

Filed under:
|
|

I have one strange problem. I have following piece of code:

template<clss index, class policy>
inline int CBase<index,policy>::func(const A& test_in, int* srcPtr ,int* dstPtr)
{
    int width = test_in.width();
    int height = test_in.height();

    double d = 0.0; //here is the problem
    for(int y = 0; y < height; y++)
    {

        //Pointer initializations

        //multiplication involving y
        //ex: int z = someBigNumber*y + someOtherBigNumber;
        for(int x = 0; x < width; x++)
        {
            //multiplication involving x
        //ex: int z = someBigNumber*x + someOtherBigNumber;
            if(soemCondition)
            {
                // floating point calculations
            }
            *dstPtr++ = array[*srcPtr++];
        }
    }
}

The inner loop gets executed nearly 200,000 times and the entire function takes 100 ms for completion. ( profiled using AQTimer)

I found an unused variable double d = 0.0; outside the outer loop and removed the same. After this change, suddenly the method is taking 500ms for the same number of executions. ( 5 times slower).

This behavior is reproducible in different machines with different processor types. (Core2, dualcore processors).

I am using VC6 compiler with optimization level O2. Follwing are the other compiler options used :

 -MD -O2 -Z7 -GR -GX -G5 -X -GF -EHa

I suspected compiler optimizations and removed the compiler optimization /O2. After that function became normal and it is taking 100ms as old code.

Could anyone throw some light on this strange behavior?

Why compiler optimization should slow down performance when I remove unused variable ?

Note: The assembly code (before and after the change) looked same.

© Stack Overflow or respective owner

Related posts about c++

Related posts about compiler-optimization