inspect.stack() performance

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Aug 13 02:53:12 EDT 2009


En Thu, 06 Aug 2009 09:00:45 -0300, Doron Tal <doron.tal.list at gmail.com>  
escribió:

> I use inspect.stack() to extract some info, such as file name, function  
> name
> and line number, for the sake of logging (home brew logger).
> I tested to see how much time it takes to execute the command:
>
> Python 2.4.3 (#1, Jan 21 2009, 01:11:33)
> [GCC 4.1.2 20071124 (Red Hat 4.1.2-42)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import timeit
>>>> t = timeit.Timer('inspect.stack()', 'import inspect')
>>>> t.repeat(3,1000)
> [0.28500604629516602, 0.28315305709838867, 0.29169297218322754]
>>>>
>
> About 280uSec per call.
>
> If I log 1000 times per seconds than I get to spend 28% of the process  
> time
> on inspect.stack()
> Is there a better/quicker way of retrieving the same info?

inspect loads the whole source code of every module in the stack (using  
linecache). If all you want is module name + line number, use this:

f = sys._getframe()
print f.f_globals['__name__'], f.f_lineno

(see a recent post about warnings.warn too)

-- 
Gabriel Genellina




More information about the Python-list mailing list