cProfile——python性能分析

本文简要介绍了Python性能分析工具cProfile的使用,包括两种调用方式:cProfile.run()和在命令行中使用。cProfile可以统计函数调用次数和耗时,帮助优化代码。通过输出的ncalls、tottime、percall、cumtime和percall等指标,可以了解代码执行效率。只需掌握基本用法,即可有效提升代码性能。
摘要由CSDN通过智能技术生成

写代码经常会听说一些名词,比如 性能分析、代码调优。

cProfile 是 python 代码调优的一种工具,它能够统计在整个代码执行过程中,每个函数调用的次数和消耗的时间。

这个工具虽然很常用,但是没必要花太多时间研究这个工具,简单使用就能达到效果,所以我这里只简单记录下核心用法。

两种使用方式

cProfile.run('func(arg)')     # 调优函数,在脚本中使用
python -m cProfile myscript.py (-s ziduan)    # 调优脚本,在命令行使用

输出解释

        9891015 function calls (9843181 primitive calls) in 12.791 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000   12.791   12.791 <string>:1(<module>)
        1    0.037    0.037    0.966    0.966 AccOverstep.py:13(AccOverstep)
        2    0.166    0.083    9.534    4.767 DataPreprocessing.py:27(dists)
        1    0.003    0.003    6.252    6.252 DataPreprocessing.py:38(DataPreprocessing)
    10909    0.004    0.000    0.167    0.000 _methods.py:34(_sum)
       10    0.000    0.000    0.000    0.000 _methods.py:45(_all)
    42360    0.071    0.000    0.092    0.000 _methods.py:48(_count_reduce_items)
    42360    0.201    0.000    0.678    0.000 _methods.py:58(_mean)

共有 9891015 次函数调用,原始调用为 9843181 次,原始调用代表不包含递归调用。

ncalls 函数的被调用次数 

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

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

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

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

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

参考资料:

https://blog.csdn.net/u010453363/article/details/78415553

高效编程之 cProfile 性能分析 - 努力的孔子 - 博客园 (cnblogs.com)https://www.cnblogs.com/yanshw/p/11593255.html(21条消息) python模块-cProfile和line_profiler(性能分析器)_loco_python-CSDN博客_cprofileicon-default.png?t=M1L8https://blog.csdn.net/weixin_40304570/article/details/79459811

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值