timeit模块:该模块可以用来测试一段python代码的执行速度/时长
Timer类:该类是timeit模块中专门用于测量python代码的执行速度/时长的。原型为class timeit.Timer(stmt=‘pass‘,setup=‘pass‘)。
stmt参数:表示即将进行测试的代码语句。
setup: 运行代码块语句时所需要的设置。
timeit函数:timeit.Timer.timeit(number=100000),该函数返回代码块语句执行number此的平均耗时。
1 from timeit import Timer 2 3 def test01(): 4 alist = [] 5 for i in range(1000): 6 alist.append(i) 7 return alist 8 9 def test02(): 10 alist = [] 11 for i in range(1000): 12 alist += [i] 13 return alist 14 15 def test03(): 16 alist = [i for i in range(1000)] 17 18 def test04(): 19 alist = list(range(1000)) 20 return alist 21 22 if __name__ == ‘__main__‘: 23 t1 = Timer(‘test01()‘,setup=‘from __main__ import test01‘) 24 second_1 = t1.timeit(1000) 25 print(‘函数1‘,second_1) 26 27 t2 = Timer(‘test02()‘,setup=‘from __main__ import test02‘) 28 second_2 = t2.timeit(1000) 29 print(‘函数2‘,second_2) 30 31 t3 = Timer(‘test03()‘,setup=‘from __main__ import test03‘) 32 second_3 = t3.timeit(1000) 33 print(‘函数3‘,second_3) 34 35 t4 = Timer(‘test04()‘,setup=‘from __main__ import test04‘) 36 second_4 = t4.timeit(1000) 37 print(‘函数4‘,second_4)
运行结果:
函数1 0.05753669999990052 函数2 0.07849220000002788 函数3 0.025955500000009124 函数4 0.01134290000004512
原文:https://www.cnblogs.com/dwdar/p/13551592.html