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

python 脚本性能查看简单方式

2016-08-27 22:42 381 查看
程序运行慢的原因有很多,比如存在太多的劣化代码(如在程序中存在大量的“.”操作符),但真正的原因往往是比较是一两段设计并不那么良好的不起眼的程序,比如对一序列元素进行自定义的类型转换等。因为程序性能影响是符合80/20法则的,即20%的代码的运行时间占用了80%的总运行时间(实际上,比例要夸张的多,通常是几十行代码占用了95%以上的运行时间),靠经验就很难找出造成性能瓶颈的代码了。这时候,我们需要一个工具——profile!最近我手上的项目也在一些关键的地方遇到了性能问题,那时已经接近项目完工日期,幸好因为平时的代码模块化程度比较高,所以通过profile分析相关的独立模块,基本上解决了性能问题。
对于大型的项目,对于脚本的性能肯定是需要提出很高的要求,那么如何去查看自己脚本运行的性能,python作为无比强大的语言当然也提供了类似性能查看的api-profile,首先必须确保已经安装了python-profile,安装过程:

  1.打开linux下的终端;

  2.输入:sudo apt-get install python-profile

安装好了,profile是python的标准库。可以统计程序里每一个函数的运行时间,并且提供了多样化的报表。使用profile来分析一个程序很简单,举例说如果有一个程序如下:

[python]
view plain
copy
print?

def test():  
        a = 0  
        for i in xrange(1,100):  
                 a += 1  
import profile  
profile.run( "test()" )  

如此大家可以查看一下结果,结果就是函数的运行时间和次数等信息,一下是我终端上打印的信息

[plain]
view plain
copy
print?

>>> profile.run("test()")  
         4 function calls in 0.004 CPU seconds  
  
   Ordered by: standard name  
  
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)  
        1    0.004    0.004    0.004    0.004 :0(setprofile)  
        1    0.000    0.000    0.000    0.000 <stdin>:1(test)  
        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.004    0.004 profile:0(test())  

[plain]
view plain
copy
print?

一下是针对上面个字段的解释:  

[plain]
view plain
copy
print?

ncalls  
函数的被调用次数  

[plain]
view plain
copy
print?

tottime  
函数总计运行时间,除去函数中调用的函数运行时间  

[plain]
view plain
copy
print?

percall  
函数运行一次的平均时间,等于tottime/ncalls  

[plain]
view plain
copy
print?

cumtime  
函数总计运行时间,含调用的函数运行时间  

[plain]
view plain
copy
print?

percall  
函数运行一次的平均时间,等于cumtime/ncalls  

[plain]
view plain
copy
print?

filename:lineno(function)  
函数所在的文件名,函数的行号,函数名  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: