Function hamming::weight

source · []
pub fn weight(x: &[u8]) -> u64
Expand description

Computes the Hamming weight of x, that is, the population count, or number of ones.

This is a highly optimised version of the following naive version:

fn naive(x: &[u8]) -> u64 {
    x.iter().fold(0, |a, b| a + b.count_ones() as u64)
}

This uses Lauradoux Cédric’s tree-merging approach (as implemented by Kim Walisch in primesieve) and achieves on the order of 1-2 cycles per byte.

Performance Comparison

lengthnaive (ns)weight (ns)naive/weight
15160.31
1029510.56
1002843920.72
1,0002,7803408.2
10,00027,7002,30012
100,000276,00017,90015
1,000,0002,770,000172,00016

Example

assert_eq!(hamming::weight(&[1, 0xFF, 1, 0xFF]), 1 + 8 + 1 + 8);