一、profile,cProfile

1. python -m cProfile myprogram.py

python -m profile myprog.py
2. 使用import profile模块
import profile
def profileTest():
    ...
if __name__ == "__main__":
    profile.run("profileTest()")

cProfile.run('func()')
3.ipython

%prun  func()

%run -p myprog.py

其中输出每列的具体解释如下:
ncalls:表示函数调用的次数;
tottime:表示指定函数的总的运行时间,除掉函数中调用子函数的运行时间;
percall:(第一个 percall)等于 tottime/ncalls;
cumtime:表示该函数及其所有子函数的调用运行的时间,即函数开始调用到返回的时间;
percall:(第二个 percall)即函数运行一次的平均时间,等于 cumtime/ncalls;
filename:lineno(function):每个函数调用的具体信息;
如果需要将输出以日志的形式保存,只需要在调用的时候加入另外一个参数。如 profile.run("profileTest()","testprof")。

对于 profile 的剖析数据,如果以二进制文件的时候保存结果的时候,可以通过 pstats 模块进行文本报表分析,它支持多种形式的报表输出,是文本界面下一个较为实用的工具。使用非常简单:
import pstats
p = pstats.Stats('testprof')
p.sort_stats("name").print_stats()
其中 sort_stats() 方法能够对剖分数据进行排序, 可以接受多个排序字段,如 sort_stats('name', 'file') 将首先按照函数名称进行排序,然后再按照文件名进行排序。常见的排序字段有 calls( 被调用的次数 ),time(函数内部运行时间),cumulative(运行的总时间)等。此外 pstats 也提供了命令行交互工具,执行 python – m pstats 后可以通过 help 了解更多使用方式。

性能分析的结果以图形的方式呈现,常见的可视化工具有 Gprof2Dot,visualpytune,KCacheGrind 等。

二、timeit

1、import timeit

t=timeit.Timer('...')

t.timeit()

class Timer( [stmt='pass' [, setup='pass' [, timer=<timer function>]]])
stmt参数是字符串形式的一个代码段,这个代码段将被评测运行时间;setup参数用以设置stmt的运行环境;timer可以由用户使用自定义精度的计时函数。
timeit.Timer有三个成员函数,下面简单介绍一下:
timeit( [number=1000000])
timeit()执行一次Timer构造函数中的setup语句之后,就重复执行number次stmt语句,然后返回总计运行消耗的时间。
repeat( [repeat=3 [, number=1000000]])
repeat()函数以number为参数调用timeit函数repeat次,并返回总计运行消耗的时间
print_exc( [file=None])
print_exc()函数用以代替标准的tracback,原因在于print_exc()会输出错行的源代码

2、python timeit.py [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...]

 其中参数的定义如下:
-n N/--number=N
       statement语句执行的次数
-r N/--repeat=N
       重复多少次调用timeit(),默认为3
-s S/--setup=S
       用以设置statement执行环境的语句,默认为”pass”
-t/--time
       计时函数,除了Windows平台外默认使用time.time()函数,
-c/--clock
       计时函数,Windows平台默认使用time.clock()函数
-v/--verbose
       输出更大精度的计时数值
-h/--help
       简单的使用帮助

3、ipython

%timeit ...

%run -t [-N<N>] myprog.py

 

posted on 2014-06-09 10:38  perel  阅读(733)  评论(0编辑  收藏  举报