如何优化以下 python 函数以更快地执行?

How to optimize the following python function to execute faster?

以下代码是使用mid-short的半固定编码。编码过程工作正常(执行需要 2 秒)。但解码过程大约需要 16 秒。我在这里只提到了解码过程。 'Main' 块中的代码只是一个示例。有没有办法让下面的代码更快?

from math import ceil, floor, log2

def semi_fixed(stream, parent):

  code_len = ceil(log2(parent + 1))
  boundary = 2 ** code_len - parent - 1  # short_code_num
  # print('Code_len: ', code_len, 'Boundary: ', boundary)
  low = floor(parent / 2) - floor(boundary / 2)
  high = floor(parent / 2) + floor(boundary / 2) + 1
  if parent % 2 == 0:
     low -= 1
  bits = stream[-code_len+1::]  # First read short code from last
  data = int(str(bits), 2)

  if low >= data or data >= high:
     bits = stream[-code_len::]
     data = int(str(bits), 2)
  else:
     code_len -= 1   # To balance the length in recursive call
  return data, code_len



if __name__ == '__main__':
  encoded_data = '011010101011011110001010'
  decoded_data = [15]
  count = 0
  while len(decoded_data) <23:
    if decoded_data[count] == 0:
      decoded_data.append(0)
      decoded_data.append(0)
      count += 1
      continue
    else:
      node, bit_len = semi_fixed(encoded_data, decoded_data[count])
      decoded_data.append(node)
      decoded_data.append(decoded_data[count] - node)
      encoded_data = encoded_data[:-bit_len]
      print(encoded_data)
      count +=1
    print(decoded_data)

半固定方法从右侧读取编码数据并决定要解码的位数。该过程持续到一定长度。这里的长度和第一个解码数据是硬编码的。上面代码的结果如下(这只是一个不到一秒的例子):

01101010101101111000
[15, 10, 5]
0110101010110111
[15, 10, 5, 8, 2]
01101010101101
[15, 10, 5, 8, 2, 3, 2]
01101010101
[15, 10, 5, 8, 2, 3, 2, 5, 3]
0110101010
[15, 10, 5, 8, 2, 3, 2, 5, 3, 1, 1]
01101010
[15, 10, 5, 8, 2, 3, 2, 5, 3, 1, 1, 2, 1]
011010
[15, 10, 5, 8, 2, 3, 2, 5, 3, 1, 1, 2, 1, 2, 0]
0110
[15, 10, 5, 8, 2, 3, 2, 5, 3, 1, 1, 2, 1, 2, 0, 2, 3]
01
[15, 10, 5, 8, 2, 3, 2, 5, 3, 1, 1, 2, 1, 2, 0, 2, 3, 2, 1]
0
[15, 10, 5, 8, 2, 3, 2, 5, 3, 1, 1, 2, 1, 2, 0, 2, 3, 2, 1, 1, 0]

[15, 10, 5, 8, 2, 3, 2, 5, 3, 1, 1, 2, 1, 2, 0, 2, 3, 2, 1, 1, 0, 0, 1]

我可以通过使用整数和按位运算获得 30% 的加速:

  code_len = parent.bit_length()
  boundary = ((1 << code_len) - parent - 1) // 2  # short_code_num
  odd = parent & 1
  parent //= 2
  low = parent - boundary + odd - 1
  high = parent + boundary + 1

还不多,但有点。

在 main 函数中,我没有在每次迭代时对 encoded_data 进行切片,而是使用了索引。索引告诉 semi_fixed 函数从哪里开始 encoded_data 作为参数传递。所以,而不是使用这个:

  node, bit_len = semi_fixed(encoded_data, decoded_data[count])
  decoded_data.append(node)
  decoded_data.append(decoded_data[count] - node)
  encoded_data = encoded_data[:-bit_len]
  print(encoded_data)
  count +=1

我使用了以下内容:

node, bit_len = semi_fixed_decoder_QA(encoded_data[:-prev_bit_len], decoded_data[count])
decoded_data.append(node)
decoded_data.append(decoded_data[count] - node)
prev_bit_len += bit_len

这里,prev_bit_len初始化为1,encoded_data右边多了一个bit . 这样我解码的时间和编码的时间几乎一样。