Python初始化list的方式对运行时间的影响比较
列表是python一种有序的集合(和C++中的数组类似),其中的元素可以随时添加和删除,是python中最基本的数据结构之一。由于python操作的简单性和灵活性,初始化list的操作方式也多种多样,但是不同的方法带来的运行时间是不一样的。
下面测试一下几种常用的列表初始化方法的实际运行时间:
1 from timeit import Timer # timeit模块常用来测试一段代码的执行耗时 2 3 def test1(): 4 li = [] 5 for i in range(10000): 6 li.append(i) 7 8 def test2(): 9 li = [] 10 for i in range(10000): 11 li = li + [i] 12 13 def test3(): 14 li = [i for i in range(10000)] 15 16 def test4(): 17 li = list(range(10000)) 18 19 def test5(): 20 li = [] 21 for i in range(10000): 22 li.extend([i]) 23 24 def test6(): 25 li = [] 26 for i in range(10000, -1, -1): 27 li.insert(0, i) 28 29 def test7(): 30 li = [] 31 for i in range(10000): 32 li.insert(-1, i) 33 34 """指定Timer的两个参数即可:1.要测试的代码段;2.代码导入方式""" 35 """测试用例都执行1000次""" 36 timer1 = Timer("test1()", "from __main__ import test1") 37 print("time cost of append:", timer1.timeit(1000)) 38 timer2 = Timer("test2()", "from __main__ import test2") 39 print("time cost of +:", timer2.timeit(1000)) 40 timer3 = Timer("test3()", "from __main__ import test3") 41 print("time cost of [i for i in range]:", timer3.timeit(1000)) 42 timer4 = Timer("test4()", "from __main__ import test4") 43 print("time cost of (list(range)):", timer4.timeit(1000)) 44 timer5 = Timer("test5()", "from __main__ import test5") 45 print("time cost of extend:", timer5.timeit(1000)) 46 timer6 = Timer("test6()", "from __main__ import test6") 47 print("time cost of pre_insert:", timer6.timeit(1000)) 48 timer7 = Timer("test7()", "from __main__ import test7") 49 print("time cost of tail_insert:", timer7.timeit(1000))
运行结果及分析:
# "append"是直接在列表尾部添加一个对象,速度还行,这种方法属于列表对象所有
time cost of append: 2.0471511209999997
# "+"相当于对两个列表相加,操作两个列表的效率很低
time cost of +: 750.211104842
# 直接用[]初始化可以获得很高的运行效率
time cost of [i for i in range]: 0.9445555839999997
# 直接用list初始化可以获得很高的运行效率
time cost of (list(range)): 0.5378683989999997
# "extend"是把每个元素分别添加到另一个列表中,运行速度和"append"相当
time cost of extend: 2.998941039
# 在列表头部插入元素,效率比较低
time cost of pre_insert: 99.273260311
# 在列表尾部插入元素,insert也会将它们视为一个整体,作为一个元素插入到列表中,和append一样
time cost of tail_insert: 3.5893552349999993