timeit模块
timeit模块可以用来测试一小段python代码的执行速度
class timeit.Timer(stmt='pass',setup='pass',timer=<timer function>)
Timer是测量小段代码执行速度的类
stmt参数是要测试的代码语句;
setup参数是运行代码需要的设置,第一个参数语句构建环境的导入语句;
timer参数是一个定时器函数,与平台有关;
timeit.Timer.timeit(number=1000000)
Timer类中测试语句执行速度的对象方法。number参数是测试代码时的测试次数,默认为1000000次,方法返回执行代码的平均耗时,一个float类型的秒数。
list的操作测试
#python列表类型不同操作的时间效率 from timeit import Timer def t1(): l1 = [] for i in range(1000): l1 += [i] def t2(): l2 = [] for i in range(1000): l2.append(i) def t3(): l3 = [i for i in range(1000)] def t4(): l4 = list(range(1000)) def t5(): l5 = [] for i in range(1000): l5.extend([i]) def t6(): l6 = [] for i in range(1000): l6.insert(-1,i) t11 = Timer("t1()","from __main__ import t1") print("+",t11.timeit(number=1000),"seconds") t22 = Timer("t2()","from __main__ import t2") print("append",t22.timeit(number=1000),"seconds") t33 = Timer("t3()","from __main__ import t3") print("列表生成器[]",t33.timeit(number=1000),"seconds") t44 = Timer("t4()","from __main__ import t4") print("list(range)",t44.timeit(number=1000),"seconds") t55 = Timer("t5()","from __main__ import t5") print("extend",t55.timeit(number=1000),"seconds") t66 = Timer("t6()","from __main__ import t6") print("insert",t66.timeit(number=1000),"seconds")
运行结果:
+ 0.18604349519765948 seconds
append 0.08720970170491515 seconds
列表生成器[] 0.03744805873315149 seconds
list(range) 0.015047234072873672 seconds
extend 0.1769862267909631 seconds
insert 0.17517417577705496 seconds