Python 不同列表时间测试

 1 import timeit
 2 import threading
 3 
 4 def test1():
 5     l = []
 6     for i in range(1000):     
 7         l = l + [i]
 8 
 9 
10 def test2():
11     l = []
12     for i in range(1000):  
13             l.append(i)
14 
15 
16 def test3():
17     l = [i for i in range(1000)]  
18 
19 
20 def test4():
21     l = list(range(1000))  
22 
26 t1 = timeit.Timer("test1()","from __main__ import test1")     
27 print("concat", t1.timeit(number = 1000),"milliseconds")
28 
29 t2 = timeit.Timer("test2()","from __main__ import test2")     
30 print("append", t2.timeit(number = 1000),"milliseconds")
31 
32 t3 = timeit.Timer("test3()","from __main__ import test3")     
33 print("comprehension", t3.timeit(number = 1000),"milliseconds")
34 
35 t4 = timeit.Timer("test4()","from __main__ import test4")     
36 print("listrange", t4.timeit(number = 1000),"milliseconds")
concat 2.0353527 milliseconds
append 0.14437619999999995 milliseconds
comprehension 0.05449919999999997 milliseconds
listrange 0.03860090000000005 milliseconds

 

上一篇:并发模式与 RPS 模式之争,性能压测领域的星球大战


下一篇:python计时函数timeit.timeit()使用小结