Python內置數據類型性能分析

timeit模塊

timeit模塊能夠用來測試一小段Python代碼的執行速度。python

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

Timer是測量小段代碼執行速度的類。app

stmt參數是要測試的代碼語句(statment);函數

setup參數是運行代碼時須要的設置;測試

timer參數是一個定時器函數,與平臺有關。spa

timeit.Timer.timeit(number=1000000)

Timer類中測試語句執行速度的對象方法。number參數是測試代碼時的測試次數,默認爲1000000次。方法返回執行代碼的平均耗時,一個float類型的秒數。code

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)) from timeit import Timer t1 = Timer("test1()", "from __main__ import test1") print("concat ",t1.timeit(number=1000), "seconds") t2 = Timer("test2()", "from __main__ import test2") print("append ",t2.timeit(number=1000), "seconds") t3 = Timer("test3()", "from __main__ import test3") print("comprehension ",t3.timeit(number=1000), "seconds") t4 = Timer("test4()", "from __main__ import test4") print("list range ",t4.timeit(number=1000), "seconds") # ('concat ', 1.7890608310699463, 'seconds') # ('append ', 0.13796091079711914, 'seconds') # ('comprehension ', 0.05671119689941406, 'seconds') # ('list range ', 0.014147043228149414, '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_zero ', 1.9101738929748535, 'seconds') # ('pop_end ', 0.00023603439331054688, 'seconds') 

測試pop操做:從結果能夠看出,pop最後一個元素的效率遠遠高於pop第一個元素blog

能夠自行嘗試下list的append(value)和insert(0,value),即一個後面插入和一個前面插入???it

list內置操做的時間複雜度

 

dict內置操做的時間複雜度

 

相關文章
相關標籤/搜索