python几个实际代码的性能分析

import profile

def test1():
    a=None
    if a==None:
        print "its none"
        
def test2():
    a=None
    if a is None:
        print "its none"
    
    
if __name__=="__main__":
    profile.run("test1()")
    profile.run("test2()")


 

运行结果:

its none
         4 function calls in 0.002 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.001    0.001    0.001    0.001 :0(setprofile)
        1    0.000    0.000    0.000    0.000 <string>:1(<module>)
        0    0.000             0.000          profile:0(profiler)
        1    0.000    0.000    0.002    0.002 profile:0(test1())
        1    0.000    0.000    0.000    0.000 test.py:3(test1)


its none
         4 function calls in 0.000 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 :0(setprofile)
        1    0.000    0.000    0.000    0.000 <string>:1(<module>)
        0    0.000             0.000          profile:0(profiler)
        1    0.000    0.000    0.000    0.000 profile:0(test2())
        1    0.000    0.000    0.000    0.000 test.py:8(test2)


 可以看出确实is None的速度远快于==None

 

再看下字符串连接中使用+和join的区别

 

from time import time



def test5(num):
    t = time()
    s = ""
    list = ['a', 'b', 'b', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
    for i in xrange (num):
        for substr in list:
            s += substr
    print "total run time +:", len(s)
    print time() - t

def test6(num):
    t = time()
    s = ""
    list = num * ['a', 'b', 'b', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
    s = s.join(list)
    print "total run time join:", len(s)
    print time() - t

if __name__ == "__main__":


    test5(10)
    test5(100)
    test5(1000)
    test5(10000)
    test5(100000)
    print "======================"
    test6(10)
    test6(100)
    test6(1000)
    test6(10000)
    test6(100000)

 

执行结果:

total run time +: 140
0.0
total run time +: 1400
0.0
total run time +: 14000
0.00300002098083
total run time +: 140000
0.0329999923706
total run time +: 1400000
0.417999982834
======================
total run time join: 140
0.0
total run time join: 1400
0.0
total run time join: 14000
0.0
total run time join: 140000
0.00200009346008
total run time join: 1400000
0.0220000743866

 


字符串长度分别从10到100000线性增长,可以明显看到无论哪个长度,join都具有明显优势

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值