尝试使用以下方法之一创建项目列表:
from pathlib import Path
list_comprehension = [item for item in Path('.').iterdir()]
list_method = list(Path('.').iterdir())
哪个更快,如何检查速度?
答案 0 :(得分:1)
您可以使用timeit
模块来实现它。
import timeit
first = """
from pathlib import Path
list_comprehension = [item for item in Path('.').iterdir()]
"""
second = """
from pathlib import Path
list_method = list(Path('.').iterdir())
"""
print(timeit.timeit(stmt=first, number=10000))
# 1.0698672000000329
print(timeit.timeit(stmt=second, number=10000))
# 1.0508478000000423
答案 1 :(得分:0)
使用以下代码检查时间
from pathlib import Path
from datetime import datetime
start_time = datetime.now()
list_comprehension = [item for item in Path('.').iterdir()]
print(datetime.now()- start_time)
start_time = datetime.now()
list_method = list(Path('.').iterdir())
print(datetime.now()- start_time)
编辑: 您应该使用 timeit 以获得更好的效果
import timeit
list_comprehension = '''
from pathlib import Path
a = [item for item in Path('.').iterdir()]'''
list_method = '''
from pathlib import Path
a = list(Path('.').iterdir())'''
print(timeit.timeit(list_comprehension, number=1000))
# 0.10110808495664969
print(timeit.timeit(list_method, number=1000))
# 0.05479578400263563