def writelines(self, list_of_data):
"""Write a list (or any iterable) of data bytes to the transport.
The default implementation concatenates the arguments and
calls write() on the result.
"""
if not _PY34:
# In Python 3.3, bytes.join() doesn't handle memoryview.
list_of_data = (
bytes(data) if isinstance(data, memoryview) else data
for data in list_of_data)
self.write(b''.join(list_of_data))
cStringIO.writelines() now accepts any iterable argument and writes
the lines one at a time rather than joining them and writing once.
Made a parallel change to StringIO.writelines(). Saves memory and
makes suitable for use with generator expressions.
我可能找到了
write
比writelines
慢的原因。在查看CPython源代码(3.4.3)时,我找到了write
函数的代码(去掉了无关部分)。在Modules/_io/fileio.c
如果您注意到了,这个函数实际上返回一个值,即已写入的字符串的大小,另一个函数调用。在
我测试了一下,看看它是否真的有返回值,它确实有。在
^{pr2}$下面是CPython中
writelines
函数实现的代码(去掉无关部分)。在Modules/_io/iobase.c
如果你注意到了,没有返回值!它只是使用
Py_RETURN_NONE
而不是另一个函数调用来计算写入值的大小。在所以,我继续测试,确实没有返回值。在
write
花费的额外时间似乎是由于实现中为生成返回值而进行的额外函数调用。通过使用writelines
,您跳过了这一步,fileio是唯一的瓶颈。在编辑:^{} documentation
这是因为在第一部分中,您必须为每个迭代中的所有行调用方法
write
,这使得您的程序需要花费大量的时间来运行。但是在第二个代码中虽然浪费了更多的内存,但是它的性能更好,因为您每100000行都调用了writelines()
方法。在让我们看看这是源,这是
writelines
函数的源:如您所见,它连接所有列表项并调用
write
函数一次。在注意,在这里加入数据需要花费时间,但是它比为每个数据调用
write
函数的时间要短行。但是由于您在中使用了Python3.4,因此它一次只写一行,而不是将它们连接起来,因此在本例中它将比write
快得多:我不同意这里的另一个答案。在
这只是一个巧合。这在很大程度上取决于您的环境:
这两段代码执行完全相同的操作,但在性能上有细微差别。在
就我个人而言,
.writelines()
比使用.write()
执行第一个示例要花更长的时间。用110MB文本文件测试。在我不会故意张贴我的机器规格。
同时也测试了大小为1.5GB的文件,结果相同。(对于1.5GB的文件,0.5GB差异最大0.5秒)。在
相关问题 更多 >
编程相关推荐