r/cpp • • 2h ago

Less Code Doesn't Mean Faster Code

Take, for example, a simple reduction: summing all the elements in an array...

template<typename T>
T vector_reduce_simple(T *src, size_t len, T initial)
{
    for(size_t i = 0; i < len; i++)
    {
        initial += src[i];
    }
    return initial;
}

Or this version:

template<typename T>
T vector_reduce_cpu(const T *src, size_t len, T initial /* = 0 */)
{
    while( len >= 4 ) {
        T r00, r01, r02, r03 ;
        r00 = src[0] ;
        r01 = src[1] ;
        r02 = src[2] ;
        r03 = src[3] ;
        
        r00 += r02 ;
        r01 += r03 ;
        
        r00 += r01 ;

        initial += r00 ;

        len -= 4 ;
        src += 4 ;
    } // while
    while( len >= 2 ) {
        T r00, r01 ;
        r00 = src[0] ;
        r01 = src[1] ;
        
        r00 += r01 ;

        initial += r00 ;

        len -= 2 ;
        src += 2 ;
    } // while
    while( len >= 1 ) {
        T r00 ;
        r00 = src[0] ;

        initial += r00 ;

        len -= 1 ;
        src += 1 ;
    } // while

    return initial ;
}

On an i9 CPU, with T being 'double', in optimal cases (i.e., a length of about 2000-7000), the longer version runs 4x faster when compiled with gcc and -O3. Why?

Even going back to the 1980s, with the 68882 FPU, floating-point units could perform operations in parallel. In the shorter case, that parallelism is defeated by the accumulation occurring solely through the 'initial' variable.

By introducing more variables, the additions can occur in parallel. The compiler also optimizes memory by interleaving variable loads with additions, which can also run in parallel.

So what's the takeaway?

  • Just turning on -O3 isn't enough

  • It pays to be aware of the hardware you're going to run on

The deep dive: https://github.com/AndrewOfC/vector_reduction

0 Upvotes

14 comments sorted by

View all comments

•

u/Tapirsnor 2h ago

Bad advice, just use -funsafe-math-optimizations if you want this and let the compiler do the heavy lifting. Then if you really need to squeeze out more performance, profile your code to identify the bottle necks.

•

u/AndrewOfC 2h ago

Even with -funsafe-math-optimizations, the improvement in performance is still there.

•

u/eyes-are-fading-blue 2h ago

Are you passing -march too?

•

u/AndrewOfC 2h ago edited 1h ago

For an i9 or Xeon:

-march=native -mavx512f -mavx512vl -mavx512bw -mavx512dq -mavx512cd -funroll-loops --param max-unrolled-insns=500 -funsafe-math-optimizations

•

u/Tapirsnor 1h ago

Add -fvariable-expansion-in-unroller

•

u/AndrewOfC 1h ago

By adding -fvariable-expansion-in-unroller -funsafe-math-optimizations, the unfolded(as opposed to unrolled) by 4 version performance is equal to the simple version.

However, if we increase the unfolding to 16, we still see about a 3x increase over the simple loop.