Search code examples
c++g++gprof

Swap 2D Double Arrays in c++


I have the following method to swap two double arrays (double**) in c++. Profiling the code, the method is accounting for 7% of the runtime... I was thinking that this should be a low cost operation, any suggestions? I am new with c++, but i was hoping to just swap the references to the arrays.

 62 void Solver::Swap(double** &v1, double** &v2)
 63 {
 64         double** vswap = NULL;
 65         vswap = v2;
 66         v2 = v1;
 67         v1 = vswap;
 68 }

Solution

  • 1) Make sure your function is inlined.

    2) You can inplace swap, using a XOR for instance

    3) Try to force the compiler to pass arguments using register instead of the stack (even though there's lot of register stress on x86, it's worth trying) - you can use the standard register keyword or play with fastcall on MS' compiler.

    typedef double** TwoDimArray;
    
    class Solver
    {
      inline void Swap( register TwoDimArray& a, register TwoDimArray& b )
      {
        a ^= b ^= a ^= b;
      }
    };
    

    4) Don't bother giving default values for temporaries like vswap.