码迷,mamicode.com
首页 > 编程语言 > 详细

Python性能分析

时间:2019-04-19 10:25:19      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:分析   函数调用   create   字符串   数据   lin   mit   entity   过程   

Python性能分析

https://www.cnblogs.com/lrysjtu/p/5651816.html
https://www.cnblogs.com/cbscan/articles/3341231.html

使用ipdb

使用profile

import profile  
def profileTest():  
   Total =1;  
   for i in range(10):  
       Total=Total*(i+1)  
       print Total  
   return Total  
if __name__ == "__main__":  
   profile.run("profileTest()")

cProfile

python -m cProfile -s cumulative -o profile.stats test_time.py

Profile的成员函数:
enable(): 开始收集性能分析数据
disable(): 停止收集性能分析数据
create_stats(): 停止收集分析数据,并为已收集的数据创建stats对象
print_stats(): 创建stats对象并打印分析结果
dump_stats(filename): 把当前性能分析的结果写入文件(二进制格式)
runcall(func, *args, **kwargs): 收集被调用函数func的性能分析数据Stats类
pstats模块提供的Stats类可以帮助我们读取和操作stats文件(二进制格式)

cProfile

在python代码中调用cProfile

import cProfile
import re
cProfile.run('re.compile("foo|bar")')

输出为:

 197 function calls (192 primitive calls) in 0.002 seconds
Ordered by: standard name
ncalls  tottime  percall  cumtime  percall filename:lineno(function)
     1    0.000    0.000    0.001    0.001 <string>:1(<module>)
     1    0.000    0.000    0.001    0.001 re.py:212(compile)
     1    0.000    0.000    0.001    0.001 re.py:268(_compile)
     1    0.000    0.000    0.000    0.000 sre_compile.py:172(_compile_charset)
     1    0.000    0.000    0.000    0.000 sre_compile.py:201(_optimize_charset)
     4    0.000    0.000    0.000    0.000 sre_compile.py:25(_identityfunction)
   3/1    0.000    0.000    0.000    0.000 sre_compile.py:33(_compile)

从分析报告结果中我们可以得到很多信息:

  • 整个过程一共有197个函数调用被监控,其中192个是原生调用(即不涉及递归调用)
  • 总共执行的时间为0.002秒
  • 结果列表中是按照标准名称进行排序,也就是按照字符串的打印方式(数字也当作字符串)
    在列表中:
  • ncalls表示函数调用的次数(有两个数值表示有递归调用,总调用次数/原生调用次数)
  • tottime是函数内部调用时间(不包括他自己调用的其他函数的时间)
  • percall等于 tottime/ncalls
  • cumtime累积调用时间,与tottime相反,它包含了自己内部调用函数的时间
  • 最后一列,文件名,行号,函数名

参考资料

http://python.jobbole.com/87621/

Python性能优化

pypy,numba,cython
ctypes,swig
cffi

参考资料

http://pypy.org/
ctypes官方文档:https://docs.python.org/3/library/ctypes.html

Python性能分析

标签:分析   函数调用   create   字符串   数据   lin   mit   entity   过程   

原文地址:https://www.cnblogs.com/weiyinfu/p/10734231.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!