gpt4 book ai didi

python-3.2 - 对于 Python 3.2 : Why does adding bytes to a bytes object take longer as more bytes are added?

转载 作者:行者123 更新时间:2023-12-01 13:23:32 25 4
gpt4 key购买 nike

我最近开始学习 Python(我小时候使用 GW BASIC 后的第一门编程语言)。我注意到在向 bytes 对象添加字节时,每个字节添加的时间比上一个要长;相比之下,当向列表对象添加整数时,每个整数的添加时间与最后一个整数相同。以下程序说明。

import time
import struct
time.clock() # for Windows

def time_list():
print("adding 9,999,999 0s to one list 9 times:")
a = []
for i in range(9):
start_time = time.clock()
for j in range(9999999):
a += [0]
end_time = time.clock()
print("loop %d took %f seconds" %(i, end_time - start_time))
print()

def time_bytes_object():
print("adding 99,999 pad bytes to a bytes object 9 times:")
a = bytes()
for i in range(9):
start_time = time.clock()
for j in range(99999):
a += struct.pack('<B', 0)
end_time = time.clock()
print("loop %d took %f seconds" %(i, end_time - start_time))
print()

time_list()
time_bytes_object()

字节对象(或 struct.pack 函数)是什么导致添加字节需要越来越多的时间?或者是否有比我的示例中使用的方式更快的方法来收集一堆字节?

谢谢你的帮助,

胜利者

最佳答案

Python 中的字节字符串(和 Unicode 字符串)是不可变的,而列表是可变的。

这意味着对字节字符串进行的每个附加( += )都必须复制该字符串;原件没有被修改(尽管稍后会被垃圾收集)。相比之下,append list的方法(也被 += 使用)实际上会修改列表。

您要的是bytearray type,它是一种可变类型,其功能与字节列表非常相似。附加到 bytearray需要(摊销)常数时间,并且它很容易与字节字符串相互转换。

关于python-3.2 - 对于 Python 3.2 : Why does adding bytes to a bytes object take longer as more bytes are added?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12359190/

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