数据结构与算法(二)

python内置类型性能分析

timeit模块

class timeit.Timer(stmt="pass",setup='pass',time=<timer function>)

Timer是测量小段代码执行速度的类

stmt参数是要测试的代码语句(statment)

setup参数是运行代码是需要的设置

timer 参数是一个定时器函数,与平台无关。

 

timeit.Timer.timeit(number=1000000)

Timer类中测试语句执行速度的对象方法,number参数是测量代码时的测试册数,默认为1000000次。方法返回执行代码的平均耗时,一个float类型的秒数。

 

 

def t1():
li = []
for i in range(10000):
li.append(i)

def t2():
li = []
for i in range(10000):
li += [i]

def t3():
li = [i for i in range(10000)]

def t4():
li = list(range(10000))

def t5():
li = []
for i in range(10000):
li.extend([i])


timer1 = timeit("t1()","from __main__ import t1",number=1000)
print("append:",timer1)

timer2 = timeit("t2()","from __main__ import t2",number=1000)
print("+:",timer2)


timer3 = timeit("t3()","from __main__ import t3",number=1000)
print("i for i in range(n):",timer3)

timer4 = timeit("t4()","from __main__ import t4",number=1000)
print("list(range(n)):",timer4)

timer5 = timeit("t5()","from __main__ import t5",number=1000)
print("li.extend([i]):",timer5)

 

posted @ 2018-07-30 15:50  红尘陌上,独自行走  阅读(109)  评论(0编辑  收藏  举报