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

时间:2014-05-26 14:51:45

标签: python python-2.7 profiling

我有一个Python脚本,使用普通逻辑从第一行到最后一行执行相当简单。在几台具有不同环境的机器上,脚本性能有很大不同,所以我试图找出代码的哪一行给我带来了困难。

我已经看到cProfiler和一些questionstimeit)记录了整个函数的执行时间。但是,我有兴趣了解Python在我的脚本中执行每行代码所花费的时间。

源代码:

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

我想得到什么(行数 - 在几秒钟内执行的时间):

1 - 0.04
2 - 0.01
3 - 0.06
4 - 0.08
5 - 0.1

编辑:我尝试使用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 Essential Reference书中的热点的例子。

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)

1 个答案:

答案 0 :(得分:2)

有一个line profiler module可能正在寻找你想要的东西。它还有很好的装饰器,您可以将它们放在逐行分析的功能上。您可以阅读文档here

另请查看hotshot。看起来您可以设置linetimings参数来获取您要查找的内容。我不确定将来版本是否支持hotshot