Assignment saves time?

Steven D'Aprano steve at
Sat Feb 16 02:08:33 CET 2008

On Fri, 15 Feb 2008 12:51:19 -0800, rpglover64 wrote:

> I ran it in an interactive python shell, which might have made a
> difference.
> import timeit
> time1=timeit.Timer('s=len(li); s==1000', 'li=range(1000)')
> time2=timeit.Timer('len(li)==1000', 'li=range(1000)')
> store=min(time1.repeat(5))
> call=min(time2.repeat(5))
> store=min(min(time1.repeat(5)),store)
> call=min(min(time2.repeat(5)),call)
> store
>   0.25531911849975586
> call
>   0.25700902938842773
> The difference is small enough to be insignificant, but I am curious how
> it's possible and why it happened.  It's more likely a reflection of how
> I timed it than anything else, isn't it?

No. It's more likely to be a reflection of the fact that on a modern, 
multitasking operating system, there are a lot of processes running, and 
timings can be unpredictable because you have little control over those 
other processes. In other words: it was probably a fluke.

Does your test *consistently* give you that result? Over and over again?

If so, then I would be wondering if there is some sort of weird caching 
or pipelining issue in your CPU, where for some reason the first result 
actually completes faster despite needing to do more work.

>>> import dis
>>> dis.dis(compile('len(li)==1000', '', 'eval'))
  1           0 LOAD_NAME                0 (len)
              3 LOAD_NAME                1 (li)
              6 CALL_FUNCTION            1
              9 LOAD_CONST               0 (1000)
             12 COMPARE_OP               2 (==)
             15 RETURN_VALUE

None of those ops correspond to machine instructions. There's lots of 
opportunity for weird interactions between Python and the underlying 
hardware. I wouldn't expect them, but nor would I discount the 


More information about the Python-list mailing list