<p>We have an entire research paper on this topic: <a href="https://arxiv.org/abs/1611.07612" rel="nofollow noreferrer">Faster Population Counts using AVX2 Instructions</a>. Despite the title, it covers SSE as well. For a relevant software library, see <a href="https://github.com/CountOnes/hamming_weight" rel="nofollow noreferrer">hamming_weight</a>. It includes all sorts of fast functions to do this type of work.</p>

<p>The short answer: you can use a Muła popcount function like so:</p>

<pre><code> __m128i popcount(__m128i v) {
    const __m128i lookup = _mm_setr_epi8(
    /* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
    /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
    /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
    /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4
);
   __m128i low_mask = _mm_set1_epi8(0x0f);
   __m128i lo  = _mm_and_si128(v, low_mask);
   __m128i hi  = _mm_and_si128(_mm_srli_epi16(v, 4), low_mask);
   __m128i popcnt1 = _mm_shuffle_epi8(lookup, lo);
   __m128i popcnt2 = _mm_shuffle_epi8(lookup, hi);
  return _mm_sad_epu8(_mm_add_epi8(popcnt1, popcnt2), _mm_setzero_si128());
}
</code></pre>

<p>The result from the <code>popcount</code> call is a 128-bit counter made of two 64-bit counters that you must add up. Summing up the two 64-bit counters can be done at the very end to save computational time.</p>
C++ SIMD: accumulate POPCOUNTs of uint64_t elements in an array
<p>I am trying to accumulate the <code>POPCOUNT</code>s for the <code>uint64_t</code> integers in an array using SSE instructions.<br>
This is my code:</p>

<pre><code>#include &lt;emmintrin.h&gt;
#include &lt;nmmintrin.h&gt;
#include &lt;chrono&gt;

int main()
{    
  uint64_t data[4] = {1,1,1,1};
  uint64_t data2[4] = {1,0,1,0};
  __m128i* ptr = (__m128i*) data;
  __m128i* ptr2 = (__m128i*) data2;

  int total = 0;
  for (int i = 0; i &lt; 2; ++i, ++ptr, ++ptr2)
    total += popcount(_mm_and_si128(*ptr, *ptr2)); // This doesn't work    
}
</code></pre>

<p>I need the equivalent of the <code>POPCOUNT</code> function which operates on the output of <code>_mm_and_si128</code>, so I can accumulate all the <code>POPCOUNT</code>s into the <code>total</code> variable.</p>