Python 列表與元組的速度比較


IPython 中用 magic 命令 %timeit 來計時。

比較生成速度

%timeit [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]

1000000 loops, best of 3: 456 ns per loop

%timeit (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25)

10000000 loops, best of 3: 23 ns per loop

可以看到,元組的生成速度要比列表的生成速度快得多,相差大概一個數量級。

比較遍歷速度

產生內容相同的隨機列表和元組:

#Python學習交流群:778463939

from numpy.random import rand
values = rand(10000,4)
lst = [list(row) for row in values]
tup = tuple(tuple(row) for row in values)

 %timeit for row in lst: list(row)

100 loops, best of 3: 4.12 ms per loop

%timeit for row in tup: tuple(row)

100 loops, best of 3: 2.07 ms per loop

在遍歷上,元組和列表的速度表現差不多。
比較遍歷和索引速度:

%timeit for row in lst: a = row[0] + 1

The slowest run took 12.20 times longer than the fastest. This could mean that an intermediate result is being cached 
100 loops, best of 3: 3.73 ms per loop

%timeit for row in tup: a = row[0] + 1

100 loops, best of 3: 3.82 ms per loop

元組的生成速度會比列表快很多,迭代速度快一點,索引速度差不多。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM