我有一个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 :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)