Odoo中文网|Odoo实施培训

 找回密码
 立即注册
搜索
热搜: Odoo OpenERP 实施
查看: 5674|回复: 0
打印 上一主题 下一主题

python list 的+、+=和extend操

[复制链接]

8

主题

8

帖子

28

积分

新手上路

Rank: 1

积分
28
跳转到指定楼层
楼主
发表于 2015-9-14 20:19:24 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
                                                                        据说后者在list很大的时候性能稍好。
于是测试了一把:
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
26
27
28
29
30
import time

def time_cost(func):
    def _time_cost(*args,**kw):
        t1=time.time()
        func(*args,**kw)
        t2=time.time()
        return t2-t1
    return _time_cost

@time_cost
def test_add(list_a,huge_list_b):
    return list_a+huge_list_b
@time_cost
def test_extend(list_a,huge_list_b):
    return list_a.extend(huge_list_b)


if __name__=='__main__':
    print '-----big list test-------------'
    a=[1]*1000
    b=['a']*(10**8)
    print 'add cost:%s seconds'%test_add(a,b)
    print 'extend cost:%s seconds'%test_extend(a,b)

    print '-----small list test-------------'
    a=[1]*1000
    b=['a']*(10**2)
    print 'add cost:%s seconds'%test_add(a,b)
    print 'extend cost:%s seconds'%test_extend(a,b)






我机器是win7,64bit,6G 内存,i3 cpu,结果如下:
1
2
3
4
5
6
-----big list test-------------
add cost:1.30500006676 seconds
extend cost:0.591000080109 seconds
-----small list test-------------
add cost:0.0 seconds
extend cost:0.0 seconds





在b为10^8长度的时候,extend所耗的时间几乎只有+操作的一半。
在1000长度的级别,相差不大。几乎相同。

+=等同于extend,如下:
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
26
import time

def time_cost(func):
    def _time_cost(*args,**kw):
        t1=time.time()
        func(*args,**kw)
        t2=time.time()
        return t2-t1
    return _time_cost

@time_cost
def test_add(list_a,huge_list_b):
    list_a+=huge_list_b
    return list_a
@time_cost
def test_extend(list_a,huge_list_b):
    return list_a.extend(huge_list_b)


if __name__=='__main__':
    print '-----big list test-------------'
    a=[1]*1000
    b=['a']*(10**8)
    a2=[1]*1000
    print '+= cost:%s seconds'%test_add(a,b)
    print 'extend cost:%s seconds'%test_extend(a2,b)




 输出:
1
2
3
-----big list test-------------
+= cost:0.506999969482 seconds
extend cost:0.510999917984 seconds


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|技术支持|开发手册|Odoo中文网-远鼎旗下odoo培训网站 ( 苏ICP备15039516号 )

GMT+8, 2024-5-9 09:47 , Processed in 0.010416 second(s), 9 queries , Xcache On.

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表