python数据结构的性能
作者:互联网
2019-11-03 16:07:33
## 对比*list*和*dict*操作
类型 | list | dict |
索引 | i | key |
添加 | append、extend、insert | d[key] = value |
删除 | pop、remove* | pop |
更新 | l[i] = value | d[key] = value |
正查 | l[i]、l[i:j] | d[key]、copy |
反查 | index(value)、count(value) | / |
其他 | reverse、sort | has_key、update |
原则上,常用操作性能最优
# list
对列表:最常用操作有
+ 按索引赋值取值:`l[i]=v` `v=l[i]`
+ 列表增长:
- append()
- __add()__
- "+"
四种生成前n个整数列表的方法
#循环连接 def test1(): l = [] for i in range(1000): l = l + [i] #append()方法 def test2(): l = [] for i in range(1000): l.append(i) #列表推导式 def test3(): l = [i for i in range(1000)] #range()函数调用转成列表 def test4(): l = list(range(1000))
性能对比
from timeit import Timer t1 = Timer("test1()", "from __main__ imporrt test1") print("concat %f seconds\n" % t1.timeit(number = 1000)) t2 = Timer("test2()", "from __main__ imporrt test2") print("append %f seconds\n" % t2.timeit(number = 1000)) t3 = Timer("test3()", "from __main__ imporrt test3") print("comprehension %f seconds\n" % t3.timeit(number = 1000)) t4 = Timer("test4()", "from __main__ imporrt test4") print("list range %f seconds\n" % t4.timeit(number = 1000))
- timeit模块Timer.timeit()方法[number]参数表示反复调用多少次
运行结果1<2<3<4
concat 1.082888 seconds append 0.054237 seconds comprehension 0.027933 seconds list range 0.011302 seconds
## list.pop操作
比较pop()和pop(i)
import timeit popzero = timeit.Timer("x.pop(0)", "from __main__ import x") popend = timeit.Timer("x.pop()", "from __main__ import x") x = list(range(2000000)) print(popzero.timeit(number=1000)) x = list(range(2000000)) print(popend.timeit(number=1000))
运行结果
1.5929707000000235 5.389999989802163e-05
比较两者时间增长趋势
print("\tpop(0)\t\t\tpop()") for i in range(1000000,100000001,1000000): x = list(range(i)) pt = popend.timeit(number=1000) x = list(range(i)) pz = popzero.timeit(number=1000) print("%15.5f, %15.5f"%(pz,pt))
pop(0) pop() 0.79530, 0.00007 1.62498, 0.00006 2.71965, 0.00007 3.78712, 0.00006 5.04768, 0.00006 6.15274, 0.00006 6.96183, 0.00007 7.83566, 0.00007 9.28867, 0.00007
肉眼可见的线性增长 : 不增长
# dict
最常用操作
- 取值get()
- 赋值set()
- 存在contains(in)
性能均为O(1)
import random for i in range(10000,100001,10000): t = timeit.Timer("random.randrange(%d) in x" % i, "from __main__ import random, x") x = list(range(i)) lst_time = t.timeit(number=1000) x = {j:None for j in range(i)} d_time = t.timeit(number=1000) print("%d,%10.3f,%10.3f" % (i,lst_time,d_time))
运行结果(规模,列表,字典)
10000, 0.047, 0.001 20000, 0.085, 0.001 30000, 0.129, 0.001 40000, 0.179, 0.001 50000, 0.220, 0.001 60000, 0.255, 0.001 70000, 0.311, 0.001 80000, 0.355, 0.001 90000, 0.376, 0.001 100000, 0.414, 0.001
肉眼可见的线性增长 : 无关规模
O(n) : O(1)
更多信息见官方wiki
https://wiki.python.org/moin/TimeComplexity
标签:__,timeit,python,性能,list,number,range,数据结构,1000 来源: https://www.cnblogs.com/ilyyfan/p/11788222.html