我很好奇如何提升性能,因此查看了Martijn Pieters和Stephen Miller的回答。
我尝试使用shutil
进行二进制模式和文本模式,并且尝试了合并270个文件。
文本模式 -
最初的回答:
def using_shutil_text(outfilename):
with open(outfilename, 'w') as outfile:
for filename in glob.glob('*.txt'):
if filename == outfilename:
continue
with open(filename, 'r') as readfile:
shutil.copyfileobj(readfile, outfile)
def without_shutil_text(outfilename):
with open(outfilename, 'w') as outfile:
for filename in glob.glob('*.txt'):
if filename == outfilename:
continue
with open(filename, 'r') as readfile:
outfile.write(readfile.read())
二进制模式 -
最初的回答
def using_shutil_text(outfilename):
with open(outfilename, 'wb') as outfile:
for filename in glob.glob('*.txt'):
if filename == outfilename:
continue
with open(filename, 'rb') as readfile:
shutil.copyfileobj(readfile, outfile)
def without_shutil_text(outfilename):
with open(outfilename, 'wb') as outfile:
for filename in glob.glob('*.txt'):
if filename == outfilename:
continue
with open(filename, 'rb') as readfile:
outfile.write(readfile.read())
二进制模式的运行时间 -
最初的回答:
Shutil - 20.161773920059204
Normal - 17.327500820159912
文本模式下的运行时间 -
最初的回答 -
Shutil - 20.47757601737976
Normal - 13.718038082122803
看起来在两种模式下,shutil执行的操作是相同的,但文本模式比二进制模式更快。
操作系统:Mac OS 10.14 Mojave。Macbook Air 2017。