应用python的性能测量工具cProfile

本文介绍如何使用Python内置模块cProfile进行代码性能分析。通过命令行和代码内使用两种方式,可详细记录函数调用次数、耗时等信息,并利用pstats模块进行结果解析。

转自:http://blog.youkuaiyun.com/ltcappui/article/details/8508360


cProfile的命令行用法

[plain]  view plain copy
  1. python -m cProfile XXX.py  
输出到指定的文件:

[plain]  view plain copy
  1. python -m cProfile -o log.txt XXX.py  

输出就被定向到了log.txt文件。

log.txt文件可以用VPT(http://visualpytune.googlecode.com)这样的图形工具打开。当log比较多的时候,可以很方便的进行过滤和时间的排序。

简单说一下log输出的阅读说明:

[plain]  view plain copy
  1.      2145 function calls (2058 primitive calls) in 0.301 seconds  
  2.   
  3. Ordered by: standard name  
  4.   
  5. ncalls  tottime  percall  cumtime  percall filename:lineno(function)  
  6.      1    0.000    0.000    0.000    0.000 _strptime.py:103(__calc_am_pm)  
  7.      1    0.000    0.000    0.000    0.000 _strptime.py:115(__calc_date_time)  
  8.      1    0.022    0.022    0.024    0.024 _strptime.py:12(<module>)  
  9.      1    0.000    0.000    0.000    0.000 _strptime.py:160(__calc_timezone)  
  10.      1    0.000    0.000    0.000    0.000 _strptime.py:176(TimeRE)  
  11.      1    0.000    0.000    0.002    0.002 _strptime.py:179(__init__)  
  12.      4    0.000    0.000    0.000    0.000 _strptime.py:212(<genexpr>)  
  13.      6    0.000    0.000    0.000    0.000 _strptime.py:221(__seqToRE)  
  14.     49    0.000    0.000    0.000    0.000 _strptime.py:236(<genexpr>)  
  15.      4    0.000    0.000    0.001    0.000 _strptime.py:240(pattern)  
  16.      1    0.000    0.000    0.001    0.001 _strptime.py:263(compile)  

输出如上图,主要有:

ncalls:  函数被call的次数
tottime:函数总的耗时,但是不包括其子函数的耗时
percall:tottime平均到每次调用的耗时
cumtime:函数总的耗时,包括了其子函数的耗时(递归函数也不例外)
percall:cumtime平均到每次调用的耗时
filename:lineno(function) :每个函数各自的信息


cProfile在python代码中使用

[python]  view plain copy
  1. import cProfile  
[python]  view plain copy
  1. cProfile.run('myfunction(arg1,arg2)''myfunction_prof')  

使用以上的代码来引入cProfile, 并且使用其作为入口来调用待测函数。结果会放在myfunction_prof文件中。

这里再介绍一下结果文件在python下的阅读方法:

[python]  view plain copy
  1. import pstats  
  2. p = pstats.Stats('myfunction_prof')  
pstats还有排序,筛选等方法,便于阅读。


以上的内容,很容易在python的reference中找到,请参考:

http://docs.python.org/2/library/profile.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值