1. timeit模块
可以用来测试一小段Python代码的执行速度。
计时器类:class timeit.Timer(stmt='pass', setup='pass', timer=<timer function>)
Timer是测量小段代码执行速度的类
stmt:是要测试的代码语句(statment),也可以传方法名
setup:运行语句时,需要的设置,例如为了执行time.time()要引入time包
timer:是一个定时器函数,与平台有关,不需要处理
函数:timeit.Timer.timeit(number=1000000)
Timer类中测试语句执行速度的对象方法
number参数是测试代码时的测试次数,默认为1000000次
方法返回执行代码的平均耗时,一个float类型的秒数
# -*- coding:utf-8 -*- def test1(): l = [] for i in range(3000): l.append(i) def test2(): l = [] for i in range(3000): l.insert(0, i) def test3(): l = [i for i in range(3000)] def test4(): l = list(range(3000)) def test5(): l = [] for i in range(3000): l.extend([i]) def test6(): l = [] for i in range(3000): l = l + [i] def test7(): l = [] for i in range(3000): l += [i] from timeit import Timer print('开始测试') t1 = Timer("test1()", "from __main__ import test1") print("append: ", t1.timeit(number=1000), "秒") t2 = Timer("test2()", "from __main__ import test2") print("insert: ", t2.timeit(number=1000), "秒") t3 = Timer("test3()", "from __main__ import test3") print("推倒: ", t3.timeit(number=1000), "秒") t4 = Timer("test4()", "from __main__ import test4") print("list: ", t4.timeit(number=1000), "秒") t5 = Timer("test5()", "from __main__ import test5") print("extend: ", t5.timeit(number=1000), "秒") t6 = Timer("test6()", "from __main__ import test6") print("+: ", t6.timeit(number=1000), "秒") t7 = Timer("test7()", "from __main__ import test7") print("+=: ", t7.timeit(number=1000), "秒") print('结束测试')