r/cpp • • 3d 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

22 comments sorted by

28

u/ta9876543205 3d ago

Someone has just discovered loop unrolling

-11

u/AndrewOfC 3d ago

or demonstrating its value

11

u/Tapirsnor 3d 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.

-3

u/AndrewOfC 3d ago

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

2

u/eyes-are-fading-blue 3d ago

Are you passing -march too?

2

u/AndrewOfC 3d ago edited 3d ago

For an i9 or Xeon:

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

5

u/Tapirsnor 3d ago

Add -fvariable-expansion-in-unroller

1

u/AndrewOfC 3d 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.

-1

u/LazySapiens 2d ago

You should code in assembly. C++ is too high level a language for you.

2

u/Cross_22 3d ago

Would love to read your findings using std::simd

3

u/AndrewOfC 3d ago

Some rough results on an i9-11950H

https://github.com/AndrewOfC/vector_reduction/blob/dev/compiler_options/imgs/i9-rough.png

With:

-march=native -funsafe-math-optimizations -fvariable-expansion-in-unroller -mavx512f -mavx512vl -mavx512bw -mavx512dq -mavx512cd -funroll-loops --param max-unrolled-insns=5000

We can get about a 3x boost over the simple loop using SIMD and the unfolded/unrolled also produces about 3x over the simple loop.

3

u/levodelellis 2d ago

It'd be less code if you used compiler supported attributes, or intrinsics

Less code is usually more readable

1

u/AndrewOfC 2d ago

If you check the repository, various methods are tried, including intrinsics, experimental SIMD, NEON, AVX and.

1

u/levodelellis 1d ago edited 1d ago

I clicked it but I didn't exactly see a tldr, also, is there any avx2 code in there? I didn't see any. I actually prefer using intrinstics explicitly. because if I'm bothering to optimize it, I don't want to accidentally lose it because someone changed a line

4

u/Unfair-Sleep-3022 3d ago

How come the compiler can't optimize it though?

14

u/parkotron 3d ago

Because the second version will give slightly different answers than the first, due to the intricacies of floating point operations.

Without passing special flags, compilers will only allow optimizations that do not affect visible behaviour.

6

u/Unfair-Sleep-3022 3d ago

Makes sense.. I didn't realize the result was different

A bit dumb to call that an optimization then

7

u/parkotron 3d ago

It is an optimization, though.

The two will give different answers, but it's pretty unlikely either answer is likely to be consistently better than the other.

5

u/UndefFox 3d ago

It is optimization in usually given constraints that float point values aren't exact in ether case/

0

u/-TheWarrior74- 1d ago

I wonder why you didn't just... use recursion here?

T reduce(T* src, size_t len) {
     if (len > 2) {
         size_t l1 = len/2; size_t l2 = (len - l1);
         return reduce(src, l1) + reduce(src + l1, l2);
     }
     else if (len == 2) {
         return src[0] + src[1];
     }

     return src[0];
}

isn't that much more parallelizable?

1

u/AndrewOfC 1d ago

Multiple approaches have been used, including recursion:

https://github.com/AndrewOfC/vector_reduction/blob/master/lib/vector_reduce_varargs.cpp

The optimizer does some interesting things with it.

-1

u/fortsnek274 3d ago

Nevermind the typical optimisations, you're playing around with bleeding edge std::simd. That's what we want to see I would expect. Whether it's any good at compile time and runtime. How it compares to MSVC/gcc/clang autovectorisation and intrinsics. And for more than reduction.