zoukankan      html  css  js  c++  java
  • cProfile分析程序性能

     Python标准库中提供了三种用来分析程序性能的模块,分别是cProfile, profile和hotshot,另外还有一个辅助模块stats。这些模块提供了对Python程序的确定性分析功能,同时也提供了相应的报表生成工具,方便用户快速地检查和分析结果。 

        这三个性能分析模块的介绍如下:

        cProfile:基于lsprof的用C语言实现的扩展应用,运行开销比较合理,适合分析运行时间较长的程序,推荐使用这个模块;

        profile:纯Python实现的性能分析模块,接口和cProfile一致。但在分析程序时增加了很大的运行开销。不过,如果你想扩展profiler的功能,可以通过继承这个模块实现;

        hotshot:一个试验性的C模块,减少了性能分析时的运行开销,但是需要更长的数据后处理的次数。目前这个模块不再被维护,有可能在新版本中被弃用。

    2种方式使用:

    cProfile.run('func(arg)','filename.txt')     # 调优函数,在脚本中使用
    python -m cProfile myscript.py [-o filename.txt]    # 调优脚本,在命令行使用   -o表示输出到文件

    输出解释

             7 function calls in 0.088 seconds
    
       Ordered by: standard name
    
       ncalls  tottime  percall  cumtime  percall filename:lineno(function)
            1    0.003    0.003    0.088    0.088 <string>:1(<module>)
            1    0.000    0.000    0.085    0.085 cProfile模块.py:14(f3)
            1    0.010    0.010    0.010    0.010 cProfile模块.py:15(<listcomp>)
            1    0.015    0.015    0.015    0.015 cProfile模块.py:17(<listcomp>)
            1    0.000    0.000    0.088    0.088 {built-in method builtins.exec}
            1    0.060    0.060    0.060    0.060 {built-in method builtins.sorted}
            1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

    共有 7次函数调用,耗时0.088秒,原始调用为 0次,原始调用代表不包含递归调用。

    ncalls 函数的被调用次数 

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

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

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

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

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

  • 相关阅读:
    Codeforces Round #251 (Div. 2) A
    topcoder SRM 623 DIV2 CatAndRat
    topcoder SRM 623 DIV2 CatchTheBeatEasy
    topcoder SRM 622 DIV2 FibonacciDiv2
    topcoder SRM 622 DIV2 BoxesDiv2
    Leetcode Linked List Cycle II
    leetcode Linked List Cycle
    Leetcode Search Insert Position
    关于vim插件
    Codeforces Round #248 (Div. 2) B. Kuriyama Mirai's Stones
  • 原文地址:https://www.cnblogs.com/hhsh/p/13546280.html
Copyright © 2011-2022 走看看