如果您想测试这样的东西,我建议您查看timeit 模块。
让我们为您的两个测试设置一个工作版本,我将添加一些性能相同的附加选项。
这里有几个选项:
def test1(file_path):
with open(file_path, "r", encoding="utf-8") as file_in:
return [line for line in file_in]
def test2(file_path):
return [line for line in open(file_path, "r", encoding="utf-8")]
def test3(file_path):
with open(file_path, "r", encoding="utf-8") as file_in:
return file_in.readlines()
def test4(file_path):
with open(file_path, "r", encoding="utf-8") as file_in:
return list(file_in)
def test5(file_path):
with open(file_path, "r", encoding="utf-8") as file_in:
yield from file_in
让我们用一个文本文件来测试它们,该文件是我在进行此类测试时碰巧拥有的莎士比亚全集的 10 倍。
如果我这样做:
print(test1('shakespeare2.txt') == test2('shakespeare2.txt'))
print(test1('shakespeare2.txt') == test3('shakespeare2.txt'))
print(test1('shakespeare2.txt') == test4('shakespeare2.txt'))
print(test1('shakespeare2.txt') == list(test5('shakespeare2.txt')))
我看到所有测试都产生相同的结果。
现在让我们计时:
import timeit
setup = '''
file_path = "shakespeare2.txt"
def test1(file_path):
with open(file_path, "r", encoding="utf-8") as file_in:
return [line for line in file_in]
def test2(file_path):
return [line for line in open(file_path, "r", encoding="utf-8")]
def test3(file_path):
with open(file_path, "r", encoding="utf-8") as file_in:
return file_in.readlines()
def test4(file_path):
with open(file_path, "r", encoding="utf-8") as file_in:
return list(file_in)
def test5(file_path):
with open(file_path, "r", encoding="utf-8") as file_in:
yield from file_in
'''
print(timeit.timeit("test1(file_path)", setup=setup, number=100))
print(timeit.timeit("test2(file_path)", setup=setup, number=100))
print(timeit.timeit("test3(file_path)", setup=setup, number=100))
print(timeit.timeit("test4(file_path)", setup=setup, number=100))
print(timeit.timeit("list(test5(file_path))", setup=setup, number=100))
在我的笔记本电脑上显示:
9.65
9.79
9.29
9.08
9.85
向我建议从性能角度选择哪一个并不重要。所以不要使用你的test2() 策略:-)
请注意,尽管从内存管理的角度来看,test5()(归功于 @tomalak)可能很重要!