c++vectordynamicadditionslowdown

Mysterious slowdown when adding doubles to dynamic vector in C++


I am experiencing some unknown slowdown when adding doubles to a very large dynamic vector of doubles in C++.

As seen below, it appears that slowdown occurs specifically due to adding a double that was calculated from a long-winded sum of cos and sin functions.

When only A_temp1 is added to the dynamic vector, there is no slowdown:

    for(int i=0;i<=imax;i++){
    // neither of these cause slowdown on their own
       A_temp1 = pi;
       A_temp2 = [long-winded sum of sin and cos operations]; 
    // no slowdown if only A_temp1 is  added
        A_dyn_vec[i] = A_temp1; 
    }

However, when A_temp2 is added to the vector, there is significant slowdown:

    for(int i=0;i<=imax;i++){
    // neither of these cause slowdown on their own
       A_temp1 = pi;
       A_temp2 = [long-winded sum of sin and cos operations]; 
    // significant slowdown 
        A_dyn_vec[i] = A_temp1 + A_temp2; 
    }

Also, when both are merged into a single A_temp value, there the same significant slowdown seen:

    for(int i=0;i<=imax;i++){
    // neither of these cause slowdown on their own
       A_temp = pi + [long-winded sum of sin and cos operations]; 
    // significant slowdown 
        A_dyn_vec[i] = A_temp;
    }

In summary, for some reason, adding A_temp1 does not cause slowdown, but A_temp2 does, even though they are both doubles.

A_temp2 specifically came from a function involving a long-winded sum of cos and sin functions. Perhaps something in the nature of how this number is stored is causing the issue, but I cannot figure out exactly why.

I would greatly appreciate if anyone has any input on why the slowdown is happening in this situation and how to avoid it.

Thank you!


Solution

  • If you are not using A_temp2 at all, I believe it is a compiler optimization and it is not even calculating the number because you are not using it. When you start using it in your second code. It can't ignore the calculation which causes the slowdown.

    Edit: I think the only way to help the excution time in your case is to make the sum of sins and cosines better. Basically just lower the number of function calls that you do. For example write sin(i)^2 + cos(i)^2 as 1. That would lower the number of function calls. Or do the following.

    temp1 = sin(i);
    temp2 = cos(i);
    do the sum operation with temp1 and temp2 instead of calling the sin and cos functions again and again.