【发布时间】: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