Python内置类型性能分析
Python内置类型性能分析
timeit模块
timeit模块可以用来测试一小段Python代码的执行速度。
class timeit.Timer(stmt='pass',setup='pass',timer=<timer function>)
Timer 是测量小段代码执行速度的类;
stmt参数是要测试的代码语句(statment);
setup参数是运行代码时需要的设置;
timer参数是一个定时器函数,与平台有关。
timeit.Timer.timeit(number=1000000)
Timer类中测试语句执行速度的对象方法。number参数是测试代码时的测试次数,默认为1000000次。方法返回执行代码的平均耗时,一个float类型的秒数。
list的操作测试
1 def test1(): 2 l = [] 3 for i in range(1000): 4 l = l + [i] 5 def test2(): 6 l = [] 7 for i in range(1000): 8 l.append(i) 9 def test3(): 10 l = [i for i in range(1000)] 11 def test4(): 12 l = list(range(1000)) 13 14 from timeit import Timer 15 16 t1 = Timer("test1()", "from __main__ import test1") 17 print("concat ",t1.timeit(number=1000), "seconds") 18 t2 = Timer("test2()", "from __main__ import test2") 19 print("append ",t2.timeit(number=1000), "seconds") 20 t3 = Timer("test3()", "from __main__ import test3") 21 print("comprehension ",t3.timeit(number=1000), "seconds") 22 t4 = Timer("test4()", "from __main__ import test4") 23 print("list range ",t4.timeit(number=1000), "seconds") 24 25 #concat 1.1343220240005394 seconds 26 #append 0.05844592100038426 seconds 27 #comprehension 0.0298581249999188 seconds 28 #list range 0.01225500100008503 seconds
list内置操作的时间复杂度
dict内置操作的时间复杂度