From a60f297903bb3cb6319ca3836e9a2c2e772359e7 Mon Sep 17 00:00:00 2001 From: Philipp Klaus Date: Thu, 30 Oct 2014 16:46:37 +0100 Subject: [PATCH] mvd_unpacker: huge speed-up for bits_set_count() --- tools/python_mvd_unpacker/mvd_unpacker/utils.py | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) 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 -- 2.43.0