- 实例化一个空列表,将0-n范围的数据添加到列表中
def test01(): alist = [] for i in range(10000): alist.append(i) return alist
def test02(): alist = [] for i in range(10000): alist += [i] return alist
def test03(): alist = [i for i in range(10000)] return alist
def test04(): alist = list(range(10000)) return alist
-
timeit模块:该模块可以用来测试一段python代码的执行速度/时长。
-
Timer类:该类是timeit模块中专门用于测量python代码的执行速度/时长的。原型为:class timeit.Timer(stmt='pass',setup='pass')。
-
stmt参数:表示即将进行测试的代码块语句。
-
setup:运行代码块语句时所需要的设置。
-
timeit函数:timeit.Timer.timeit(number=100000),该函数返回代码块语句执行number次的平均耗时
-
from timeit import Timer
def test01():
alist = []
for i in range(10000):
alist.append(i)
return alist
def test02():
alist = []
for i in range(10000):
alist += [i]
return alist
def test03():
alist = [i for i in range(10000)]
return alist
def test04():
alist = list(range(10000))
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)
t3 = Timer('test03()', setup='from __main__ import test03')
second_3 = t3.timeit(1000)
print(second_3)
t4 = Timer('test04()', setup='from __main__ import test04')
second_4 = t4.timeit(1000)
print(second_4)
#0.82598802
#0.9852309690000001
#0.40580514600000006
#0.2559222590000001
- 计算运行平均耗时