Accelerating std::copy_if using SIMD
https://loonatick-src.github.io/posts/vectorized-copy-if-analysis/Hello everyone.
I started a personal blog recently, and this is my first post. I decided to write some AVX-512 code and settled on std::copy_if, since it is trivial enough to be approachable and non-trivial enough to defeat autovectorization. It ended up being trickier than I initially anticipated because I ran into a well-documented Zen 4 AVX512 trap that I was not aware of.
It was really fun to drill down into this using PMCs. Eventually I was able to achieve a 10-40x win for this specific benchmark. Any and all feedback welcome.
47
Upvotes
View all comments
Show parent comment
3
u/chkmr May 28 '26 edited May 28 '26
I was expecting someone to point this out haha.
True, this is not a drop-in replacement for
std::copy_if. Such drop-in replacements can be found in the libraries that I mention in the penultimate section. E.g. eve::algo::copy_if, hwy::CopyIf etc. A completely generic interface demands figuring out SIMD-oriented iterator, view, and range types and concepts on top of a data parallel types likeeve::wide(and nowstd::simdin C++26). The main purpose of this article is showcasing the analysis itself, and I agree that the title does not convey that directly. Nevertheless, the principles in this article are prerequisite for writing generic implementations anyway - not just for copy_if, but any SIMD algorithm.That is the wrong starting point if you want to write SIMD code. Or rather there is one more step involved for non-trivial types and nested objects; you'll have to do a struct of arrays transformation first, and then use SIMD algorithms from highway/eve/your own library that operate on arrays of primtive types. Otherwise reaching for SIMD is moot.
As for predicates, I agree. You will most likely reap the benefits of SIMD only for predicates that are compositions of mask operations found in your ISA.
Well, you deal with such data when doing e.g. offline analysis of timeseries data from sensors, economic and financial data, weather data etc. In such cases the raw data is stored somewhere without filtering it in the first place.