Re: can profile be called from class method?

Guido.van.Rossum@cwi.nl
Tue, 13 Sep 1994 10:54:46 +0200

> I'm having some trouble calling the profiler from a class method.
> I want to do something like:
>
> profile.run (self.method())
>
> For the right context, it looks like I really need to use profile.runctx,
> but I don't know how to get the dictionary of locals for the 3rd argument.
>
> Can anyone set me straight on how to do this?

I suppose you meant

profile.run ('self.method()')

since your example would call self.method() before entering the
profiler.

If you really want to profile a single call, try

profile.runcall(self.method)

or (if you want to call self.method(arg1, arg2, ...))

profile.runcall(self.method, arg1, arg2, ...)

If you really need to profile an arbitrary expression in the current
context, you can use vars() to access the dictionary of local
variables. The globals are a bit more difficult, but if you know that
the global variable __name__ is the name of the current module and
sys.modules is a dictionary mapping module names to modules, and
vars() takes an optional module argument, then you'll understand that
vars(sys.modules[__name__]) returns the current global dicttionary.
So it would be

import sys

profile.runctx('self.method()',
vars(sys.modules[__name__]),
vars())

--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>
<URL:http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>