Python:分析代码块

时间:2015-05-08 20:56:06

标签: python profiling

我有一个Python函数,我想找到最慢的地方。我没有使用cProfile,但我还有其他功能。

我不想将我的功能分成十几个子功能:它看起来有点笨重而烦人。

是否有办法逐行分析功能?或者在我要描述执行时间的每个代码块之前和之后添加timer_start(timer_id)timer_stop(timer_id)之类的内容?

1 个答案:

答案 0 :(得分:0)

如果你还没有使用IPython,你应该看看。它具有像import Tkinter, Tkconstants, tkFileDialog filename = 'no-file' class TkApp(Tkinter.Frame): def __init__(self, root): Tkinter.Frame.__init__(self, root) # options for buttons button_opt = {'fill': Tkconstants.BOTH, 'padx': 5, 'pady': 5} # define buttons Tkinter.Button(self, text='Open File', command=self.askopenfilename).pack(**button_opt) Tkinter.Button(self, text='Print File Path', command=self.printing(filename)).pack(**button_opt) Tkinter.Button(self, text='Quit', command=self.quit).pack(**button_opt) # define options for opening or saving a file self.file_opt = options = {} options['defaultextension'] = '.twb' options['filetypes'] = [('All', '*')] options['initialdir'] = 'C:\\' options['parent'] = root options['title'] = 'Select a File' def askopenfilename(self): """Returns an opened file in read mode. This time the dialog just returns a filename and the file is opened by your own code. """ global filename # get filename filename = tkFileDialog.askopenfilename(**self.file_opt) # open file on your own if filename: print "askopenfilename value: " + filename return filename def printing(self, stringToPrint): print "Value on click: " + stringToPrint def quit(self): root.destroy() if __name__=='__main__': root = Tkinter.Tk() root.title("Path Printer") TkApp(root).pack() root.mainloop() 这样的神奇功能,可以轻松进行逐行分析。看看Timing and Profiling in IPython