Post · 11 min read· pp. 11–18

SSSE3: fast popcount

Contents

Introduction

Population count is a procedure of counting number of ones in a bit string. Intel introduced instruction popcnt with SSE4.2 instruction set. The instruction operates on 32 or 64-bit words.

However SSSE3 has powerful instruction PSHUFB. This instruction can be used to perform a parallel 16-way lookup; LUT has 16 entries and is stored in an XMM register, indexes are 4 lower bits of each byte stored in another XMM register.

Vector algorithm

With help of PSHUFB we can get a vector that contains population count for 16 nibbles. To get a vector of population count for each 16 byte, instruction PSHUFB have to be called twice on vectors of lower and higher nibbles, and finally added together.

Following code shows the idea:

text
; xmm0 - input (16 bytes)
; xmm7 - POPCOUNT_4bit  -- lookup table
; xmm6 - MASK_bits03 = packed_byte(0x0f) -- mask 4 lower bits

movdqa  %%xmm0, %%xmm1
psrlw       $4, %%xmm1

pand    %%xmm6, %%xmm0  ; xmm0 - lower nibbles
pand    %%xmm6, %%xmm1  ; xmm1 - higher nibbles

movdqa  %%xmm7, %%xmm2  ; since instruction pshufb modifies LUT
movdqa  %%xmm7, %%xmm3  ; it must be saved for further use

pshufb  %%xmm0, %%xmm2  ; xmm2 = vector of popcount for lower nibbles
pshufb  %%xmm1, %%xmm3  ; xmm3 = vector of popcount for higher nibbles

paddb   %%xmm3, %%xmm2  ; xmm2 += xmm3 -- vector of popcount for bytes

The last step is adding all bytes from vector.

Instruction PSADBW calculate sum of absolute differences of unsigned bytes — if the first arguments is full of zeros, then result is a sum of bytes from second argument. Unfortunately PSADBW invoked with 128-bits arguments calculate separate sums for bytes 0..7 and 8..15, and finally stores them in the lower and the higher quad words. Because of that few additional instructions are needed:

text
pxor    %%xmm0, %%xmm0  ; xmm0 = packed_byte(0x00)
psadbw  %%xmm0, %%xmm3  ; xmm3 = [popcount of bytes 0..7 | popcount of bytes 8..15]
movhlps %%xmm3, %%xmm0  ; xmm0 = [         0             | popcount of bytes 0..7 ]
paddd   %%xmm3, %%xmm0  ; xmm0 = [     not needed        | popcount of bytes 0..15]

Further improvements

PSADBW has 3 or 4 cycles latency, also additional instructions need some time to execute (I guess around 2 cycles).

PSADBW doesn't need to be called in every iteration — since max values of popcount for single byte is 8, we can perform up to floor(255/8)=31 parallel additions (PADDB) without overflow. Moreover, partial sums returned by PSADBW could be added together in the end.

Pseudocode:

text
pxor %%xmm5, %%xmm5             // global accumulator

while (bytes to end > 0) {
        pxor %%xmm4, %%xmm4     // local accumulator (for inner loop)

        n = min(bytes to end/16, 31)    // up to 31 blocks
        for (i=0; i < n; i++) {
                // calculate xmm3, a vector of popcount for bytes

                paddb %%xmm3, %%xmm4    // xmm4 += xmm3 -- update local acc.
        }

        pxor   %%xmm0, %%xmm0
        psadbw %%xmm4, %%xmm0   // xmm4 -- calculate two popcounts

        // update global acc.
        paddd  %%xmm4, %%xmm5
}

// add halfs of global accumulator
movhlps %%xmm5, %%xmm0
paddd   %%xmm5, %%xmm0
movd    %%xmm0, %%eax   // eax = population count for all bytes

Source code

Github repository contains the original code from 2008 and also the new C++11 (2015, 2016), intrinsics-based implementation.

Experiments (64-bit code)

Program from the repository were run with default settings (make run and make run_avx2) and repeated several times. Minimal measurements were considered.

Below is the list of procedures listed in here. The repository has more variants.

procedureimplementation
lookup-8LUT-based procedure (uint8_t[266])
lookup-64LUT-based procedure (uint8_t[266]), avoid zero-extend
bit-parallelwell know method, described for example in Bit Twiddling Hacks
bit-parallel-optimizedabove + the trick from section "Further improvements"
harley-sealHarley-Seal variant
sse-bit-parallelSSE variant of bit-parallel
sse-lookupthe method described in this text using SSE instructions
sse-lookupthe method described in this text using AVX2 instructions
cpupopcnt instruction emitted via intrinsic

Core i5 (Westmere)

The CPU architecture: Core i5 M540 @ 2.53GHz (Westmere)

More details in a separate file.

procedure32 B64 B128 B256 B512 B1024 B2048 B4094 B
lookup-82.298842.200392.150862.128303.409853.386323.373343.36643
lookup-642.298372.199792.150672.126083.401123.381353.371653.36490
bit-parallel2.136452.006521.934061.905673.012412.996612.991122.99828
bit-parallel-optimized1.378121.239701.161831.138771.790161.770861.759891.78260
harley-seal1.476581.299220.794240.634320.901970.861940.834910.85399
sse-bit-parallel2.694182.400011.407930.956521.170031.001290.923820.86693
sse-lookup0.755280.541950.349420.310780.472110.456940.446500.46007
cpu0.492830.377990.320580.291850.443600.432130.426370.36332

CPU popcnt outperforms the code described here.

Core i7 (Haswell)

The CPU architecture: Haswell i7-4770 CPU @ 3.40GHz.

More details in a separate file.

procedure32 B64 B128 B256 B512 B1024 B2048 B4094 B
lookup-81.204081.109381.063121.107221.699221.663151.641131.63397
lookup-641.177751.099941.063741.091021.675791.645481.623901.61094
bit-parallel1.267681.105531.052221.026261.620861.610241.604951.61435
bit-parallel-optimized1.002330.825450.722460.674541.041131.023661.017081.03801
harley-seal1.002600.795970.501160.394400.545530.502770.481390.48978
sse-bit-parallel2.152062.020081.093930.667770.757170.611790.537910.49923
sse-lookup0.535200.339020.213790.180610.266880.256050.250540.25780
avx2-lookup0.530680.339200.213730.135790.171330.155000.142930.17005
cpu0.294800.240510.154780.132700.200520.194620.208430.21684

AVX2 code is faster than the dedicated instruction for input size 512 bytes and larger.

Core i7 (Skylake)

The CPU architecture: Skylake i7-6700 CPU @ 3.40GHz

More details in a separate file.

procedure32 B64 B128 B256 B512 B1024 B2048 B4094 B
lookup-81.029560.948361.046710.956231.460181.423731.406331.39675
lookup-641.007040.943871.032330.947441.456291.423711.407471.39947
bit-parallel1.056620.952970.909920.889081.405871.397531.393371.41585
bit-parallel-optimized0.812780.690910.633290.604530.944430.933200.927600.95122
harley-seal0.812830.663970.433480.340350.468710.430770.411810.41767
sse-bit-parallel2.254321.709800.924430.576180.681890.582200.501690.45568
sse-lookup0.407490.298020.182900.157420.239560.230570.226570.23177
avx2-lookup0.433500.263680.179500.115870.148810.137290.127980.14222
cpu0.216760.162560.135460.121920.184230.220650.196430.20293

Again AVX2 code is faster than the dedicated instruction for input size 256 bytes and larger.

Experiments (32-bit code) — outdated

Note 2016-03-13: this section refers to results from 2008.

ssse3_popcount.c is a test program that contains implementations of following procedures:

  • lookup — popcount based on LUT with 256 entries; I tested GCC __builtin_popcount, however it was much slower than my implementation
  • ssse3-1 — straightforward SSSE3 implementation
  • ssse3-2 — improved SSSE3 implementation
  • ssse3-unrl — ssse3-2 with inner loop unrolled 4 times
  • sse2-1 — SSE2 bit-level parallel implementation
  • sse2-2 — improved SSE2 implementation (using the same tricks as SSSE3 version)
  • see2-unrl — ssee2-2 with inner loop unrolled 4 times

The first argument of the program is a function name, the second is the number of 16-byte chunks processed by the selected procedure in one iteration and the third is the iterations number.

The table shows results for different chunk count; test script I've used is available. Program was compiled with following options:

text
gcc -O2 -DALIGN_DATA ssse3_popcount.c -o ssse3_popcount

Tests were run on my Linux box, with Core 2 Duo E8200;

chart

Results clearly show, that the method presented above brings significant speedup, which depends on the data size.

The straightforward SSSE3 implementation is 2-2.8 times faster, the improved around 3 times, and the unrolled 4-5 times.

procedurenumber of 16-byte chunksiterationstime [s]speedup
lookup120,000,0000.22100%
sse2-10.19115%
sse2-20.20110%
ssse3-10.14157%
ssse3-20.16137%
lookup820,000,0001.42100%
sse2-10.92154%
sse2-20.79179%
ssse3-10.61232%
ssse3-20.52273%
lookup322,000,0000.55100%
sse2-10.34161%
sse2-20.30183%
sse2-unrl0.22250%
ssse3-10.22250%
ssse3-20.19289%
ssse3-unrl0.12458%
lookup128200,0000.21100%
sse2-10.13161%
sse2-20.11190%
sse2-unrl0.08262%
ssse3-10.08262%
ssse3-20.07299%
ssse3-unrl0.04525%
lookup512200,0000.86100%
sse2-10.53162%
sse2-20.45191%
sse2-unrl0.34252%
ssse3-10.34252%
ssse3-20.26330%
ssse3-unrl0.18477%
lookup1024200,0001.73100%
sse2-11.07161%
sse2-20.90192%
sse2-unrl0.68254%
ssse3-10.69250%
ssse3-20.52332%
ssse3-unrl0.38455%
lookup2048200,0003.47100%
sse2-12.14162%
sse2-21.80192%
sse2-unrl1.37253%
ssse3-11.38251%
ssse3-21.06327%
ssse3-unrl0.76456%

Acknowledgments

Daniel Lemire has gave me access to computers with Haswell and Skylake processors, thanks to that I could play with AVX2 code and run tests. Kim Walisch contributed the Harley-Seal implementation. There were some fixes and enhancements to sample code by various people. Thank you.

See also

  • Population count using XOP instructions

  • Paper by Daniel Lemire, Nathan Kurz and me: Faster Population Counts using AVX2 Instructions.

  • Hacker news discussion.

  • Speeding up bit-parallel population count — delaying byte-wise sum (the trick with PSADBW) applied for bit parallel method gives 50% speedup over plain, SWAR 64-bit procedure.

  • Anatomy of High-Performance 2D Similarity Calculations — paper contains interesting comparison of similarity calculations which heavily use popcount operation. The authors compared 4 basic methods: 1) hardware-based, i.e. popcnt instruction, 2) simple LUT, 3) bit-level parallel method (SSE2 procedure), and 4) the method described here. The most important observation, from my point of view of course, is that the speed of SSSE3 code is comparable to hardware popcnt, it is just a bit slower.

    The authors published also the full source code and I noticed they manually unrolled inner loop. I did the same in my code and speedup increased from 3 to 4-5 — sources and article has been updated.

  • Benchmarking CRC32 and PopCnt instructions — Peter Kankowski compared speed of SSE4.2 instructions crc32 and popcnt against software implementations. Hardware CRC32 is significantly faster, but population count is slightly slower than the algorithm presented here

Changelog

  • 2016-03-16 — detailed results from Westmere, Haswell & Skylake
  • 2016-03-13 — AVX2 implementation, results from Westmere and Skylake, wording
  • 2015-03-04 — link to github repo
  • 2011-10-22 — link to paper, unrolled loops
  • 2010-06-28 — link to Peter's site
  • 2010-03-27 — SSE2 procedures