python 自动记录时间_在Python脚本中记录每一行的执行时间?

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值