【问题标题】:Log time of execution for each line in Python script?记录Python脚本中每一行的执行时间?
【发布时间】:2014-05-26 14:51:44
【问题描述】:

我有一个 Python 脚本,它从第一行到最后一行执行相当简单,逻辑很简单。在不同环境的几台机器上,脚本的性能差异很大,所以我试图找出哪一行代码让我很难受。

我见过cProfiler 和一些questions (timeit) 记录整个函数的执行时间。但是,我有兴趣了解 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 book 中找到了另一个使用热点的示例。

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)

【问题讨论】:

    标签: python python-2.7 profiling


    【解决方案1】:

    有一个line profiler module 可以满足您的需求。它还具有不错的装饰器,您可以逐行放置要分析的功能。你可以阅读文档here

    还可以查看hotshot。看起来您可以设置 linetimings 参数来获取您要查找的内容。不过,我不确定hotshot 是否会在未来的版本中得到支持。

    【讨论】:

    • 好一个。核心 Python 中包含什么?我很有可能无法在其中一台机器上安装任何东西。
    • @AlexTereshenkov 添加了更多信息。我认为你可以用 hotshot 得到你想要的,它是内置在 Python 中的。让我知道你的效果如何。
    • 非常感谢。我已经尝试过了,并用代码和错误消息更新了我的答案。在 Internet 上很难找到 hotshot 的任何示例用法,我只看到了 Python 官方文档附带的示例。你有没有机会指出我上面的代码有什么问题?
    猜你喜欢
    • 2016-07-14
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多