小编Gil*_*ash的帖子

Python - 以最有效的方式对"字节"中的每个字节进行"xor"

我有一个"字节"对象和一个"int"掩码,我想用我的掩码对所有字节做xor.我在大"字节"对象(~4096 KB)上反复执行此操作.

这是我的代码,它可以很好地工作,只是它非常占用CPU并且减慢了我的脚本:

# 'data' is bytes and 'mask' is int
bmask = struct.pack('!I', mask) # converting the "int" mask to "bytes" of 4 bytes 
a = bytes(b ^ m for b, m in zip(data, itertools.cycle(bmask)))
Run Code Online (Sandbox Code Playgroud)

我能想到的最好的是这个,大约快20倍:

# 'data' is bytes and 'mask' is int
# reversing the bytes of the mask
bmask = struct.pack("<I", mask)
mask = struct.unpack(">I", bmask)[0]

# converting from bytes to array of "int"s
arr = array.array("I", data)

# looping over the "int"s
for i in …
Run Code Online (Sandbox Code Playgroud)

python performance

9
推荐指数
1
解决办法
1178
查看次数

标签 统计

performance ×1

python ×1