您的位置:首页 > 编程语言 > Python开发

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

2013-07-13 15:03 471 查看
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都具有明显优势

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: