python - 我还是不明白memoryview的观点
问题描述
我通读了问题和答案或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 最终也必须复制切片。
如果您不做愚蠢的事情,那么坚持使用字节似乎要简单得多。
解决方案
您的前两个基准测试基本上从左侧蚕食一个字节,直到什么都没有。
例如bytes
,这做了 N 份副本,对于 memoryview 永远不会有副本,只是调整视图的长度
你的最后一个例子完全不相似,而不是蚕食一个字节,你蚕食了越来越多的字节(b[1:]
b[2:]
b[3:]
)——最终字符串被用尽,你正在切割一个空字符串(更准确地说是什么时候i * (i + 1) / 2 > n
)。例如,对于 100,000 字节序列,您在 446 次迭代后执行 noops。
推荐阅读
- 3d - 如何读取关于串口数据的xml?我无法解决这个问题
- c - 如何创建原始(十六进制)位图数据,是否可以在没有其他程序的情况下查看它们?
- php - 未捕获的 RainTpl_NotFoundException
- java - Google YouTube API:播放列表列表和 quotaExceeded
- python - 如何为气流中的任务添加重试功能
- java - 如何使用自定义 setView 为 AlertDialog 设置 OnClickListener?
- javascript - nodejs - __dirname 不替换为正则表达式?
- sql - SQL - 将 DECIMAL 转换为 FRACTION 并规范化?
- php - 在 Heroku 上打开 Symfony 应用程序时出现 SQLite 错误
- javascript - 如何为电子应用程序制作一个有效的保存按钮?