timeit模块
timeit模块
用途:用来测试一段python代码的执行速度
Timer类
该类是timeit模块中专门用于测量python代码的执行速度/时长的。
from timeit import Timer
Timer(stmt='pass',setup='pass')
('test01()',setup='from __main__ import test01')
stmt参数:表示即将进行测试的代码块语句。
setup:运行代码块语句时所需要的设置。
timeit函数:
timeit.Timer.timeit(number=100000)
该函数返回代码块语句执行number次的平均耗时。
示例:
from timeit import Timer
def test01():
alist = []
for i in range(1000):
alist.append(i)
return alist
def test02():
alist = []
for i in range(1000):
alist += [i]
return alist
def test03():
alist = [i for i in range(1000)]
return alist
def test04():
alist = list(range(1000))
return alist
if __name__ == '__main__':
t1 = Timer('test01()',setup='from __main__ import test01')
second_1 = t1.timeit(1000)
print(second_1)
t2 = Timer('test02()',setup='from __main__ import test02')
second_2 = t2.timeit(1000)
print(second_2)