Python性能分析

Python性能分析

http://www.javashuo.com/article/p-cmjhwjeg-ea.html
https://www.cnblogs.com/cbscan/articles/3341231.htmlhtml

使用ipdbpython

使用profileweb

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文件(二进制格式)ide

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
cfficode

参考资料

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

相关文章
相关标签/搜索