字节的高效查找 table

Efficient lookup table for bytes

我需要将原始字节解包为位。现在我有一个原始数据和一个查找 table。迭代输入数据以生成输出的最有效方法是什么?或者也许还有另一种方法可以做到这一点?

#Look up table looks something like this.
lookup = {
  0: b'\x00\x00\x00\x00\x00\x00\x00\x00',
  1: b'\x00\x00\x00\x00\x00\x00\x00\x01',
  2: b'\x00\x00\x00\x00\x00\x00\x01\x00',
  ...
  255: b'\x01\x01\x01\x01\x01\x01\x01\x01',
}

def remap(data):
  out = [lookup(byte) for byte in data]
  row = b''.join(out)

以下是最耗时的函数:

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
44000    2.843    0.000    2.843    0.000 main.py:59(<listcomp>)
44007    0.593    0.000    0.593    0.000 {method 'join' of 'bytes' objects}

原来我的猜测大错特错。但是这些评论有有趣的读物来解释为什么会这样。


这里我给出了两个微不足道的改进,希望可以稍微提高运行时性能。

首先,您的查找 table 将自然数作为键。这是一个列表。

lookup = [
  b'\x00\x00\x00\x00\x00\x00\x00\x00',
  b'\x00\x00\x00\x00\x00\x00\x00\x01',
  b'\x00\x00\x00\x00\x00\x00\x01\x00',
  ...
  b'\x01\x01\x01\x01\x01\x01\x01\x01',
]

其次,不用构造列表然后输入加入,而是使用generator.

def remap(data):
    return b''.join(lookup[byte] for byte in data)

但你可能也想测试这个问题的想法:

Converting integer to binary in python


也许这也符合您的需要,但它给出的是列表而不是 bstring。

https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.unpackbits.html#numpy.unpackbits