gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 07:18:33 25 4
gpt4 key购买 nike

以下代码是关于使用 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
还不是很多,但有些东西。

关于python - 如何优化以下python函数以更快地执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68639707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com