Profiling problem

Bernhard Herzog herzog at online.de
Fri May 7 17:55:40 EDT 1999


Randall Hopper <aa8vb at vislab.epa.gov> writes:

> Why does the following example fail to resolve "self"?
> 
> (It's contrived, but it demonstrates my problem.)
> 
> I'd like to profile just a portion of a multi-module app, and after
> browsing the profile section in libref and the "exec" description in
> langref, I'm still not sure why this doesn't work.
> 
> Thanks,
> 
> Randall
> 
> 
> >>> class C:
> ...    def slow_dog( self ):
> ...       import time
> ...       time.sleep(5)
> ...    def doit( self ):
> ...       import profile
> ...       profile.run( 'self.slow_dog()' )
> ... 
> >>> c = C()
> >>> c.doit()
> Traceback (innermost last):
[snip]
> NameError: self


The source is your friend, here. From profile.py:

	# The following two methods can be called by clients to use
	# a profiler to profile a statement, given as a string.
	
	def run(self, cmd):
		import __main__
		dict = __main__.__dict__
		return self.runctx(cmd, dict, dict)
	
	def runctx(self, cmd, globals, locals):
		self.set_cmd(cmd)
		sys.setprofile(self.dispatcher)
		try:
			exec cmd in globals, locals
		finally:
			sys.setprofile(None)
		return self


The run method runs your code in the global namspace of the __main__
module, so it can't refer to local variables.

In your case, you have to use the runctx method, e.g. like this:

	profile.runctx('self.slow_dog()', globals(), locals())


-- 
Bernhard Herzog	  | Sketch, a python based drawing program
herzog at online.de  | http://www.online.de/home/sketch/




More information about the Python-list mailing list