timeit模块
timeit模块可以用来测试一小段python代码的执行速度。
class timeit.Timer(stmt=“pass”,setup=“pass”,timer=)
Timer 是测量一小段代码执行速度的类。
stmt参数是要测试的代码语句
setup参数是运行代码时需要的设置
timer参数是一个定时器函数,与平台有关。
list的操作测试
def t1():
l = []
for i in range(1000):
l = l + [i]
def t2():
l = []
for i in range(1000):
l.append(i)
def t3():
l = [i for i in range(1000)]
def t4():
l = list(range(1000))
from timeit import Timer
timer1 = Timer("t1()","from __main__ import t1")
print("concat",timer1.timeit(number=1000),"seconds")
timer2 = Timer("t2()","from __main__ import t2")
print("append",timer2.timeit(number=1000),"seconds")
timer3 = Timer("t3()","from __main__ import t3")
print("comprehension",timer3.timeit(number=1000),"seconds")
timer4 = Timer("t4()","from __main__ import t4")
print("list range",timer4.timeit(number=1000),"seconds")
运行结果:
concat 1.0428046000000002 seconds
append 0.11417100000000002 seconds
comprehension 0.032680299999999995 seconds
list range 0.013189899999999977 seconds
pop操作测试
x = range(2000000)
pop_zero = Timer("x.pop(0)","from __main__ import x")
print("pop_zero",pop_zero.timeit(number=1000),"seconds")
x = range(2000000)
pop_end = Timer("x.pop()","from __main__ import x")
print("pop_end",pop_end.timeit(number=1000),"seconds")
运行结果:
pop最后一个元素的效率远远高于pop第一个元素
list 内置操作的时间复杂度
dict 内置操作的时间复杂度