[Python-talk] Using timeit

Kent Johnson kent37 at tds.net
Wed Oct 14 15:01:43 EDT 2009


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.

> 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


More information about the Python-talk mailing list