r/Cplusplus • • 18d ago

Tutorial Reduction Algorithm With Recursing Template

As part of an exploration on optimizing x64 AVX and Arm NEON vector extensions.

https://github.com/AndrewOfC/vector_reduction

inline static auto reduce(auto a, auto b) 
// terminal case for recursion
{
    return a + b ;
}

inline static auto reduce(auto a, auto b, auto... args) 
// consume two arguments and recurse
{
    return reduce(reduce(a, b), args...) ;
}


template<typename T>
T va_reduce(T *src, size_t len, T initial)
{
    while( len >= 32 ) {
        initial += reduce(src[0], src[1], src[2], src[3], src[4], src[5], src[6], src[7], src[8], src[9], src[10], src[11], src[12], src[13], src[14], src[15], src[16], src[17], src[18], src[19], src[20], src[21], src[22], src[23], src[24], src[25], src[26], src[27], src[28], src[29], src[30], src[31]) ;
        len -= 32 ;
        src += 32 ;
    } 
// while
    
while( len >= 16 ) {
        initial += reduce(src[0], src[1], src[2], src[3], src[4], src[5], src[6], src[7], src[8], src[9], src[10], src[11], src[12], src[13], src[14], src[15]) ;
        len -= 16 ;
        src += 16 ;
    } 
// while
    
while( len >= 8 ) {
        initial += reduce(src[0], src[1], src[2], src[3], src[4], src[5], src[6], src[7]) ;
        len -= 8 ;
        src += 8 ;
    } 
// while
    
while( len >= 4 ) {
        initial += reduce(src[0], src[1], src[2], src[3]) ;
        len -= 4 ;
        src += 4 ;
    } 
// while
    
while( len >= 2 ) {
        initial += reduce(src[0], src[1]) ;
        len -= 2 ;
        src += 2 ;
    } 
// while

    
if( len != 0 )
        initial += src[0] ;

    return initial ;
}
4 Upvotes

2 comments sorted by

1

u/8Erigon 18d ago

How does that optimize?

1

u/AndrewOfC 18d ago

By 'unfolding' the reduce calls(by 32, 16, 8, 4, 2) into separate variables as the recursion descends the optimizer at -O3 is able to take advantage of parallelism in the CPU.

I was a little surprised myself to see this vararg implementation work as well as it did, as just a simple

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;
}

with a single variable doesn't get optimized at all(or at least as much as it could).

Still, for on a Xeon 6975P-C we get a speedup of about 17x with the vararg technique, but for the non-vararg implementation case we see a 20x improvement over the simplistic case. It tells you something about the complex heuristics at play within the optimizer.