]> jspc29.x-matter.uni-frankfurt.de Git - mvdsensorcontrol.git/commitdiff
mvd_unpacker: huge speed-up for bits_set_count()
authorPhilipp Klaus <klaus@physik.uni-frankfurt.de>
Thu, 30 Oct 2014 15:46:37 +0000 (16:46 +0100)
committerPhilipp Klaus <klaus@physik.uni-frankfurt.de>
Thu, 30 Oct 2014 15:46:37 +0000 (16:46 +0100)
tools/python_mvd_unpacker/mvd_unpacker/utils.py

index 8682cfd475e24f123f25bbb8de282615b64c78a9..ae881de989651448901ed7a98889f9e35afe7256 100644 (file)
@@ -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