timeit模块
timeit模块可以用来测试一小段Python代码的执行速度。
class timeit.Timer(stmt='pass', setup='pass', timer=<timer function>)
Timer是测量小段代码执行速度的类。
stmt参数是要测试的代码语句(statement);
setup参数是运行代码时需要的设置;
timer参数是一个定时器函数,与平台有关。
timeit.Timer.timeit(number=1000000)
Timer类中测试语句执行速度的对象方法。number参数是测试代码时的测试次数,默认为1000000次。方法返回执行代码的耗时,一个float类型的秒数。
举例
from timeit import Timer# 直接代码timer = Timer('print("a",end=",")')print(timer.timeit()) # 默认100万次timer = Timer('print(b,end=",")', 'b=2')print(timer.timeit(number=5)) # 2,2,2,2,2,1.9295682939906674e-05# 方法def t(): print("t",end=",")timer = Timer('t()', 'from __main__ import t')print(timer.timeit(number=5)) #t,t,t,t,t,1.68324042667271e-05# 比较列表几种添加元素的方法 + append insert 列表推导式 list()方法def t1(): li = [] for i in range(1000): li = li + [i]def t2(): li = [] for i in range(10000): li.append(i)def t3(): li = [] for i in range(10000): li.insert(0, i)def t4(): li = [i for i in range(1000)]def t5(): li = list(range(10000))timer = Timer('t1()', 'from __main__ import t1')print("+", timer.timeit(number=1000))timer2 = Timer('t2()', 'from __main__ import t2')print("append", timer2.timeit(number=1000))timer3 = Timer('t3()', 'from __main__ import t3')print("insert", timer3.timeit(number=1000))timer4 = Timer('t4()', 'from __main__ import t4')print("i for i in range", timer4.timeit(number=1000))timer5 = Timer('t5()', 'from __main__ import t5')print("list(range(10000)", timer5.timeit(number=1000))# + 1.7064962406261983# append 1.0096170504865387# insert 24.474472632563394# i for i in range 0.03823213773997125# list(range(10000) 0.2569790843007844# 列表推导式真是快,insert真是慢