在使用cProfile分析的python脚本中,tottime和cumtime有什么区别?

2024-05-16 09:17:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用cProfile和以下命令分析python脚本main.py

python -m cProfile -s tottime main.py

我得到的输出是(仅复制粘贴输出的顶行):

10184337 function calls (10181667 primitive calls) in 13.597 seconds

Ordered by: internal time

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    1    4.674    4.674   13.598   13.598 main.py:2(<module>)
 2142    2.964    0.001    4.663    0.002 load_aerdat3.py:61(getPacket)
  459    2.381    0.005    2.381    0.005 {waitKey}
1667989    1.170    0.000    1.170    0.000 {numpy.core.multiarray.array}

...

既然这个函数(即整个脚本)只调用一次,那么tottime(4.674)与cumtime(13.598)的main.py有何不同?


Tags: inpy命令脚本mainfunctioncprofileseconds
1条回答
网友
1楼 · 发布于 2024-05-16 09:17:32

tottime是仅在函数中花费的总时间。cumtime是在函数中花费的总时间加上此函数调用的所有函数。

如果一个函数从未调用其他函数,这两个值将是相同的。例如,{waitKey}似乎不会调用其他任何内容:

  459    2.381    0.005    2.381    0.005 {waitKey}

但是getPacket()调用其他函数,因此cumtime列包含这些调用的时间:

 2142    2.964    0.001    4.663    0.002 load_aerdat3.py:61(getPacket)

main.py行覆盖了在函数(全局代码)之外运行的所有代码;只有该级别的语句需要4.674秒才能运行,但由于这些语句调用了其他函数,因此main.py代码加上所有函数调用的累计时间是13.598秒。

documentation

tottime
for the total time spent in the given function (and excluding time made in calls to sub-functions)

[...]

cumtime
is the cumulative time spent in this and all subfunctions (from invocation till exit). This figure is accurate even for recursive functions.

相关问题 更多 >