在 Forth 中,我使用了一个查找表来计算每个字节的位数。
我正在寻找是否有一个 numpy 函数来计算位数并找到了这个答案。
256 字节查找比这里的两种方法快。 16 位(65536 字节查找)再次更快。我用完了 32 位查找 4.3G 的空间 :-)
这可能对找到此答案的其他人有用。其他答案中的一个衬线打字速度要快得多。
import numpy as np
def make_n_bit_lookup( bits = 8 ):
""" Creates a lookup table of bits per byte ( or per 2 bytes for bits = 16).
returns a count function that uses the table generated.
"""
try:
dtype = { 8: np.uint8, 16: np.uint16 }[ bits ]
except KeyError:
raise ValueError( 'Parameter bits must be 8, 16.')
bits_per_byte = np.zeros( 2**bits, dtype = np.uint8 )
i = 1
while i < 2**bits:
bits_per_byte[ i: i*2 ] = bits_per_byte[ : i ] + 1
i += i
# Each power of two adds one bit set to the bit count in the
# corresponding index from zero.
# n bits ct derived from i
# 0 0000 0
# 1 0001 1 = bits[0] + 1 1
# 2 0010 1 = bits[0] + 1 2
# 3 0011 2 = bits[1] + 1 2
# 4 0100 1 = bits[0] + 1 4
# 5 0101 2 = bits[1] + 1 4
# 6 0110 2 = bits[2] + 1 4
# 7 0111 3 = bits[3] + 1 4
# 8 1000 1 = bits[0] + 1 8
# 9 1001 2 = bits[1] + 1 8
# etc...
def count_bits_set( arr ):
""" The function using the lookup table. """
a = arr.view( dtype )
return bits_per_byte[ a ].sum()
return count_bits_set
count_bits_set8 = make_n_bit_lookup( 8 )
count_bits_set16 = make_n_bit_lookup( 16 )
# The two original answers as functions.
def text_count( arr ):
return sum([ bin(n).count('1') for n in arr ])
def unpack_count( arr ):
return np.unpackbits(arr.view('uint8')).sum()
np.random.seed( 1234 )
max64 = 2**64
arr = np.random.randint( max64, size = 100000, dtype = np.uint64 )
count_bits_set8( arr ), count_bits_set16( arr ), text_count( arr ), unpack_count( arr )
# (3199885, 3199885, 3199885, 3199885) - All the same result
%timeit n_bits_set8( arr )
# 3.63 ms ± 17.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit n_bits_set16( arr )
# 1.78 ms ± 15.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit text_count( arr )
# 83.9 ms ± 1.05 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit unpack_count( arr )
# 8.73 ms ± 87.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)