Skip to content

numpy/unpackbits-popcount

Rule unpackbits-popcount
Pack NumPy
Severity warning
Fix none, edit by hand
Library versions NumPy 2.0 and later

Unpacking every byte into eight bits to count the set ones was 37 times slower. Use np.bitwise_count.

ones = np.unpackbits(masks.view(np.uint8)).sum()
ones = np.bitwise_count(masks).sum()

The rule reports np.unpackbits(...).sum(), np.sum(np.unpackbits(...)) and np.count_nonzero(np.unpackbits(...)). np.bitwise_count, added in NumPy 2.0, counts the set bits of each value, and ran 37 times faster on 1,000,000 uint64 values.

xpd has no automatic fix. Because the view, reshape and axis around unpackbits vary. Make the change by hand.

xpd prints this message with the issue. A name that starts with $ stands for code from your file.

This unpacks every byte into eight before it counts the set bits. Write $NP.bitwise_count(x), summed as needed, which ran 37 times faster on 1,000,000 uint64 values.

Browse the other rules of the NumPy pack.