[Python-talk] Using timeit

Bruce Labitt bruce.labitt at myfairpoint.net
Wed Oct 14 18:43:43 EDT 2009


Kent Johnson wrote:
> On Wed, Oct 14, 2009 at 2:05 PM,  <bruce.labitt at autoliv.com> wrote:
>   
>> Is it possible to use timeit in running code?
>>     
>
> Sure :-)
>
>   
>>  This is what I'm trying to
>> do.
>>
>> import timeit
>>
>> s = """\
>> cmd = 4
>> fftdatareal = pack( fmt, cmd, *realX )
>> cmd = 5
>> fftdataimag = pack( fmt, cmd, *imagX )
>> """
>> t = timeit.Timer(stmt=s)
>> print "%.2f sec" % t.timeit(number=1)
>>
>> This give a NameError: global name 'pack' is not defined
>>     
>
> The code you give to timeit runs in its own namespace (not the
> namespace of the module running it from. Use the setup parameter to do
> any required initialization, including imports. In this case, you need
> something like
>
> t = timeit.Timer(stmt=s, setup='from struct import pack')
>
>   
>> Will fftdatareal and fftdataimag be populated using this construction?
>>     
>
> Not in the local namespace, no. You can hack this though. If this code
> is running in __main__, then change the setup to 'from struct import
> pack; import __main__' and change the timed code to assign to
> __main__.fftdatareal, etc.
>
>   
Groan, that is kind of kludgey...
>> Will the stdout have the time in seconds for the packing?
>>     
>
> Yes.
>
> You could also just call time.time() before and after your code and
> report the difference, which is pretty much what timeit is doing in
> this case.
>
> Kent
>
>   
After 20 minutes of frustration, I did just that.  Good enough for what 
I needed.

Thanks,
Bruce



More information about the Python-talk mailing list