from timeit import Timer
def test1():
L = []
for i in range(1,1000):
L = L + [i]
def test2():
L = []
for i in range(1,1000):
L += [i]
def test3():
L = [x for x in range(1000)]
def test4():
L = []
for i in range(1000):
L.append(i)
def test5():
L = []
for i in range(1000):
L.extend([i])
def test6():
L = list(range(1000))
t1 = Timer('test1()',"from __main__ import test1")
print('+',t1.timeit(1000))
t2 = Timer('test2()','from __main__ import test2')
print('+=',t2.timeit(1000))
t3 = Timer('test3()','from __main__ import test3')
print('[]',t3.timeit(1000))
t4 = Timer('test4()','from __main__ import test4')
print('append',t4.timeit(1000))
t5 = Timer('test5()','from __main__ import test5')
print('extend',t5.timeit(1000))
t6 = Timer('test6()','from __main__ import test6')
def test1():
L = []
for i in range(1,1000):
L = L + [i]
def test2():
L = []
for i in range(1,1000):
L += [i]
def test3():
L = [x for x in range(1000)]
def test4():
L = []
for i in range(1000):
L.append(i)
def test5():
L = []
for i in range(1000):
L.extend([i])
def test6():
L = list(range(1000))
t1 = Timer('test1()',"from __main__ import test1")
print('+',t1.timeit(1000))
t2 = Timer('test2()','from __main__ import test2')
print('+=',t2.timeit(1000))
t3 = Timer('test3()','from __main__ import test3')
print('[]',t3.timeit(1000))
t4 = Timer('test4()','from __main__ import test4')
print('append',t4.timeit(1000))
t5 = Timer('test5()','from __main__ import test5')
print('extend',t5.timeit(1000))
t6 = Timer('test6()','from __main__ import test6')
print('list',t6.timeit(1000))
打印结果:
('+', 2.1945629119873047)
('+=', 0.1813831329345703)
('[]', 0.0545501708984375)
('append', 0.1101219654083252)
('extend', 0.20518112182617188)
('list', 0.015774965286254883)
list最快