多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
![](https://img.kancloud.cn/41/e0/41e066af9a6c25a24868d9667253ec98_1241x333.jpg) ***** ## 代码执行时间测量模块 ``` li = [] li.append() li.insert() ``` ### timeit模块 timeit模块可以用来测试一小段Python代码的执行速度。 ``` class timeit.Timer(stmt='pass', setup='pass', timer=<timer function>) Timer是测量小段代码执行速度的类。 stmt参数是要测试的代码语句(statment); setup参数是运行代码时需要的设置; timer参数是一个定时器函数,与平台有关。 ``` timeit.Timer.timeit(number=1000000) Timer类中测试语句执行速度的对象方法。number参数是测试代码时的测试次数,默认为1000000次。方法返回执行代码的平均耗时,一个float类型的秒数。 ### list的操作测试 ``` def test1(): l = [] for i in range(1000): l = l + [i] def test2(): l = [] for i in range(1000): l.append(i) def test3(): l = [i for i in range(1000)] def test4(): l = list(range(1000)) def test5(): li = [] for i in range(1000): li.insert(0, i) from timeit import Timer t1 = Timer("test1()", "from __main__ import test1") print("add", t1.timeit(number=1000)) t2 = Timer("test2()", "from __main__ import test2") print("append ",t2.timeit(number=1000)) t3 = Timer("test3()", "from __main__ import test3") print("list derivation",t3.timeit(number=1000)) t4 = Timer("test4()", "from __main__ import test4") print("list range ",t4.timeit(number=1000)) t5 = Timer("test5()", "from __main__ import test5") print("list insert ",t5.timeit(number=1000)) ```