繁体   English   中英

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

[英]Log time of execution for each line in Python script?

我有一个Python脚本,使用普通逻辑从第一行到最后一行执行起来都非常简单。 在具有不同环境的几台计算机上,脚本性能有很大不同,因此,我试图找出哪一行代码给我带来了麻烦。

我已经看到了cProfiler和一些有关记录整个函数执行时间的问题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参考书中找到了关于使用热点的另一个示例。

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)

有一个行探查器模块可以满足您的需求。 它还具有漂亮的装饰器,您可以逐行放置要配置的功能。 您可以在此处阅读文档。

还要看看hotshot 看起来您可以设置linetimings参数以获取所需的内容。 不过,我不确定将来的版本是否会支持hotshot

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM