Find Related products on Amazon

Shop on Amazon

Improving on std:count_if()'s auto-vectorization

Published on: 2025-10-29 00:44:19

The problem Let’s consider the problem with the following description: We have an array of arbitrary length filled with uint8_t values; We want to count the number of even values in the array; Before doing the calculation we know that the number of even values in the array is between 0 and 255. A typical solution To start off, we can leverage the STL for this calculation. std::count_if() more precisely: 1 2 3 4 5 6 7 8 auto count_even_values_v1 ( const std :: vector < uint8_t > & vec ) { return std :: count_if ( vec . begin (), vec . end (), []( uint8_t x ) { return x % 2 == 0 ; } ); } Let’s take a look at the assembly (generated by Clang 19.1.0 with flags -O3 -march=rocketlake -fno-unroll-loops ). This is the main loop which counts the even numbers: 1 2 3 4 5 6 7 8 9 10 11 12 13 .LCPI0_1: .byte 1 count_even_values_v1 (): ; ............ vpbroadcastb xmm1 , byte ptr [ rip + .LCPI0_1 ] .LBB0_6: vmovd xmm2 , dword ptr [ rsi + rax ] vpandn xmm2 , xmm2 , xmm1 vpmovzxbq ymm2 , xmm2 vp ... Read full article.