r/cpp • u/mr_gnusi • Apr 15 '26
How std::abs and two compiler flags let Clang auto-vectorize L1 distance faster than Faiss's AVX2 intrinsics
https://blog.serenedb.com/simd-distancesWhen building a vector search for SereneDB [https://github.com/serenedb/serenedb], we benchmarked our distance functions against Faiss. The results were surprising, a plain C++ loop with no intrinsics came out faster. The answer comes down to two compiler flags and one standard library call.
Full write-up with assembly: https://blog.serenedb.com/simd-distances
68
Upvotes
11
u/max0x7ba https://github.com/max0x7ba Apr 15 '26
You should read CPU optimization reference manuals from Intel and AMD how to maximize SIMD compute.
That involves reading enough data to keep the CPU execution units fully utilised and let the hardware prefetcher do its best for you to minimise execution stalls due to data cache misses.
Aligned loads are +30% faster.
As well as using huge-pages to minimize TLB cache misses that stall the hardware prefetcher. memcpy is +50% faster when using 2MB huge pages instead of 4kB pages. See https://github.com/max0x7ba/thp-usage
73
u/wearingdepends Apr 15 '26
This article confuses a number of things. The benchmark machine is reported to be a Zen 5, yet the article tries to justify the poor speed up by appealing to port 5 pressure, which is a specific Intel phenomenon.
The linked Godbolt explains a lot of what's going on. The main loop of
fvec_L1is this:The main issue here is that a Zen 5 can execute 4
vandpsper cycle, as well as 2v{add,sub}psper cycle. And you also have to consider instruction latency. Here the loop is unrolled twice, because without specific tuning Clang will optimize for, IIRC, the Intel Sandy Bridge, but this leaves some performance on the table. If you pass the flag-mtune=znver5to the compiler, however, it does know this and results in a loop unrolled 8 times:Meanwhile the main loop for
L1DistanceImpl4, despite being more unrolled due to the manual unrolling in place there, results in worse code generation because it induces unnecessary vector permutations and will use comparisons instead ofvandpsto clear signs:1
u/OmegaNaughtEquals1 Apr 16 '26
Which compiler are you using? I couldn't get gcc to generate similar code without
-funsafe-math-optimizations -mfma -funroll-loops, but it tends to be much more conservative than clang.https://godbolt.org/z/Tjr9MYfox
-3
u/Sopel97 Apr 15 '26
this amount of incompetence is inexusable from such a large company as facebook
-7
u/teo-tsirpanis Apr 15 '26
Auto vectorizatoon exists mostly to make microbenchmarks look good, and has limited utility in real-world apps.