dict和list的效能對比

2021-08-19 11:38:55 字數 1778 閱讀 2591

#coding=utf-8

import

time

import

profile

#explain: cookbook, 5.12  檢查序列的成員

def

addunique

(baselist

, otherlist):

basedict

= dict

.fromkeys(baselist)

for

other

in

otherlist:

if

other

not in

basedict:

basedict

[other] =

none

def

addunique_******

(baselist

, otherlist):

for

other

in

otherlist:

if

other

not in

baselist:

if

__name__ ==

'__main__'

: a =

range(1

, 100

) b =

range(90

, 110)

# start = time.time()

profile.run(

'addunique(a, b)')

# end = time.time()

# print 'res:', a

# print 'b: ', b

# print 'spend_time', end - start

a =

range(1

, 100

) b =

range(90

, 110)

# start = time.time()

profile.run(

"addunique_******(a, b)")

# end = time.time()

# print 'res:', a

# print 'b: ', b

# print '****** spend_time', end - start

addunique: 消耗的時間就正比於兩個列表的長度之和, 一是dict.fromkeys(baselist) 時間正比於baselist的長度,

二: for迴圈,正比於otherlist的長度。

addunique_******: 消耗的時間就正比於兩個列表的長度的乘積。 在for迴圈內巢狀一層otherlist的複雜度o(n)。

效能優化:

python 字典中使用了 hash table,因此查詢操作的複雜度為 o(1),而 list 實際是個陣列,在 list 中,查詢需要遍歷整個 list,其複雜度為 o(n),因此對成員的查詢訪問等操作字典要比 list 更快。

python deque和list的效能對比

使用list儲存資料時,按索引訪問元素很快,但是插入和刪除元素就很慢了,因為list是線性儲存,資料量大的時候,插入和刪除效率很低。deque是為了高效實現插入和刪除操作的雙向列表,適合用於佇列和棧 例子 每次擴充套件1億長度的list,看deque和list的效能。coding utf 8 fro...

python效能對比

1 coding utf8 import datetime road nodes for i in range 5000000 road nodes i beg time datetime.datetime.now for key,val in road nodes.items pass end t...

SSD效能對比

ssd效能測試 順序寫 16k iops 85061.08 順序寫 8k iops 146250.93 順序寫 4k iops 239816.69 順序寫 2k iops 294540.87 順序寫 1k iops 347170.06 隨機寫 16k iops 21865.24 隨機寫 8k iop...