From: Philipp Klaus Date: Thu, 30 Oct 2014 15:46:37 +0000 (+0100) Subject: mvd_unpacker: huge speed-up for bits_set_count() X-Git-Url: https://jspc29.x-matter.uni-frankfurt.de/git/?a=commitdiff_plain;h=a60f297903bb3cb6319ca3836e9a2c2e772359e7;p=mvdsensorcontrol.git mvd_unpacker: huge speed-up for bits_set_count() --- diff --git a/tools/python_mvd_unpacker/mvd_unpacker/utils.py b/tools/python_mvd_unpacker/mvd_unpacker/utils.py index 8682cfd..ae881de 100644 --- a/tools/python_mvd_unpacker/mvd_unpacker/utils.py +++ b/tools/python_mvd_unpacker/mvd_unpacker/utils.py @@ -1,6 +1,7 @@ #!/usr/bin/python import codecs +import struct def split_by_n( seq, n ): """A generator to divide a sequence into chunks of n units.""" @@ -31,14 +32,11 @@ def str_32bit_chunks(data): def bits_set_count(x): """ Accepts bytes as input and returns the number of bits set in the bytes. + For performance optimization, len(x) must be a multiple of 8! """ - if type(x) == bytes: - sum = 0 - for b in x: - sum += bin(b).count('1') - return sum - if type(x) == int: - return bin(x).count('1') - else: - raise TypeError() + assert len(x)%8 == 0 + s = 0 + for n in struct.unpack('Q'*(len(x)//8), x): + s += bin(n).count('1') + return s