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

来源:互联网 发布:千兆端口和百兆端口 编辑:程序博客网 时间:2024/04/28 23:42
import profiledef 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 timedef 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() - tdef 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() - tif __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都具有明显优势

 

原创粉丝点击