數據結構與算法(二)
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)
數據結構與算法(二)