对于大型的项目,对于脚本的性能肯定是需要提出很高的要求,那么如何去查看自己脚本运行的性能,python作为无比强大的语言当然也提供了类似性能查看的api-profile,首先必须确保已经安装了python-profile,安装过程:

  1.打开linux下的终端;

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


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

    1. def
    2. 0
    3. for i in xrange(1,100):  
    4. 1
    5. import
    6. profile.run( "test()"

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

      1. >>> profile.run("test()")  
      2.          4 function calls in 0.004 CPU seconds  
      3.   
      4.    Ordered by: standard name  
      5.   
      6.    ncalls  tottime  percall  cumtime  percall filename:lineno(function)  
      7.         1    0.004    0.004    0.004    0.004 :0(setprofile)  
      8.         1    0.000    0.000    0.000    0.000 <stdin>:1(test)  
      9.         1    0.000    0.000    0.000    0.000 <string>:1(<module>)  
      10.         0    0.000             0.000          profile:0(profiler)  
      11.         1    0.000    0.000    0.004    0.004 profile:0(test())


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

      1. ncalls  
      2. 函数的被调用次数

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


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



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


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

          1. filename:lineno(function)  
          2. 函数所在的文件名,函数的行号,函数名