Question about timeit

Frank Millman frank at chagford.com
Fri Jul 22 08:30:07 EDT 2011


On Jul 22, 10:34 am, Stefan Behnel <stefan... at behnel.de> wrote:
> Thomas Rachel, 22.07.2011 10:08:
>
>
>
>
>
> > Am 22.07.2011 08:59 schrieb Frank Millman:
>
> >> My guess is that it is something to do with the console, but I don't
> >> know what. If I get time over the weekend I will try to get to the
> >> bottom of it.
>
> > I would guess that in the first case, python (resp. timeit.py) gets the
> > intended code for execution: int(float('165.0')). I. e., give the string to
> > float() and its result to int().
>
> > In the second case, however, timeit.py gets the string
> > 'int(float("165.0"))' and evaluates it - which is a matter of
> > sub-microseconds.
>
> > The reason for this is that the Windows "shell" removes the "" in the first
> > case, but not the '' in the second case.
>
> Good call. Or maybe it actually gets the code 'int(float(165.0))' in the
> second case, so it doesn't need to parse the string into a float. But given
> the huge difference in the timings, I would second your guess that it just
> evaluates the plain string itself instead of the code.
>
> Stefan- Hide quoted text -
>
> - Show quoted text -

This is what I get after modifying timeit.py as follows -

    if args is None:
        args = sys.argv[1:]
+       print(args)

C:\>python -m timeit int(float('165.0'))
["int(float('165.0'))"]
100000 loops, best of 3: 3.43 usec per loop

C:\>python -m timeit int(float("165.0"))
['int(float(165.0))']
1000000 loops, best of 3: 1.97 usec per loop

C:\>python -m timeit "int(float('165.0'))"
["int(float('165.0'))"]
100000 loops, best of 3: 3.45 usec per loop

It seems that the lesson is -

1. Use double-quotes around the command itself - may not be necessary
if the command does not contain spaces.
2. Use single-quotes for any literals in the command.

Frank



More information about the Python-list mailing list