在Python脚本中记录每一行的执行时间?

2024-06-28 23:52:30 发布

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

我有一个Python脚本,它从第一行到最后一行都执行得非常简单。在不同环境的几台机器上,脚本的性能是非常不同的,所以我试图找出哪一行代码给我带来了困难。在

我已经看到了cProfiler和一些{a2}(timeit)记录整个函数的执行时间。不过,我有兴趣找出Python在执行脚本中每一行代码上花费的时间。在

源代码:

import math
result = pow(2,5)
newlist = []
newlist.append(result)
print newlist

我想要得到的(行数-执行所用的时间,以秒为单位):

^{pr2}$

编辑:我试图使用hotshot,一个可用的标准库,但是我收到了一条错误消息。在

我运行的源代码:

import hotshot
import hotshot.stats

logfile = r"C:\testlog.prof"
prof_obj = hotshot.Profile(logfile,lineevents=True,linetimings=False)
prof_obj.start()
a = 1000
b = 2000
c = a + b
print c
prof_obj.stop()
prof_obj.close()

stats_obj = hotshot.stats.load(logfile) #getting error on this line *
stats_obj.strip_dirs()
stats_obj.sort_stats('time', 'calls')
stats_obj.print_stats(20)

*     for event in log:
  File "C:\Python27\ArcGIS10.2\Lib\hotshot\log.py", line 115, in next
    filename, firstlineno, funcname = self._stack[-1]
IndexError: list index out of range

编辑:我发现了另一个使用Python基本参考书中hotshot的例子。在

import hotshot
import hotshot.stats

def function_to_call():
    print "AA"
    print "BB"

logfile = r"C:\testlog.prof"
prof_obj = hotshot.Profile(logfile,lineevents=True,linetimings=True)
prof_obj.runcall(function_to_call)
prof_obj.close()

stats_obj = hotshot.stats.load(logfile)
stats_obj.sort_stats('time', 'calls')
stats_obj.print_stats()

但是,这并没有提供每行代码的任何执行信息,只提供每个函数调用的信息:

5 function calls in 0.012 seconds

   Ordered by: internal time, call count

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        4    0.012    0.003    0.012    0.003 <string>:6(write)
        1    0.000    0.000    0.012    0.012 c:\gis\temp\simple_hotshot.py:11(function_to_call)
        0    0.000             0.000          profile:0(profiler)

Tags: 代码import脚本trueobjtimestats时间
1条回答
网友
1楼 · 发布于 2024-06-28 23:52:30

有一个line profiler module可以满足您的需要。它也有很好的装饰器,你可以把你想要的函数放在一行一行的水平上。您可以阅读文档here。在

另请看一下^{}。看起来您可以设置linetimings参数来获得您要查找的内容。不过,我不确定hotshot在将来的版本中是否受支持。在

相关问题 更多 >