我通读了问题和答案或Python 中的 memoryview 到底是什么。我仍然不明白这一点。
答案中的示例起初似乎是合乎逻辑的,但是当我构造第三个测试用例时,我bytes
按索引扫描对象时,它的速度与使用memoryview
.
import time
# Scan through a bytes object by slicing
for n in (100000, 200000, 300000, 400000):
data = b'x' * n
start = time.time()
b = data
while b:
b = b[1:]
print('bytes sliced ', n, time.time() - start)
# Scan through a bytes object with memoryview
for n in (100000, 200000, 300000, 400000):
data = b'x' * n
start = time.time()
b = memoryview(data)
while b:
b = b[1:]
print('memoryview ', n, time.time() - start)
# Scan through a bytes object by index
for n in (100000, 200000, 300000, 400000):
data = b'x' * n
start = time.time()
b = data
for i in range(n):
b = b[i+1:]
print('bytes indexed ', n, time.time() - start)
输出:
bytes sliced 100000 0.16396498680114746
bytes sliced 200000 0.6180000305175781
bytes sliced 300000 1.541727066040039
bytes sliced 400000 2.8526365756988525
memoryview 100000 0.02300119400024414
memoryview 200000 0.04699897766113281
memoryview 300000 0.0709981918334961
memoryview 400000 0.0950019359588623
bytes indexed 100000 0.027998924255371094
bytes indexed 200000 0.05700063705444336
bytes indexed 300000 0.08800172805786133
bytes indexed 400000 0.1179966926574707
其中一个论点是,您可以简单地将 memoryview 对象传递给struct.unpack
. 但是你绝对可以对字节对象做同样的事情。据我了解,归结为 memoryview 最终也必须复制切片。
如果您不做愚蠢的事情,那么坚持使用字节似乎要简单得多。