Assignment saves time?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Feb 15 18:28:04 EST 2008


En Fri, 15 Feb 2008 18:51:19 -0200, <rpglover64 at gmail.com> escribió:

> 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?

Yes, I think it's an artifact of how you measured it. I've tried this:

import timeit
time1=timeit.Timer('s=len(li); s==1000', 'li=range(1000)')
r1 = time1.repeat(5)
print 'store', min(r1), r1
time2=timeit.Timer('len(li)==1000', 'li=range(1000)')
r2 = time2.repeat(5)
print 'call', min(r2), r2

and got the expected results:

store 0.336916842783 [0.33712636661922118, 0.34131209413486907,
0.33691684278309109, 0.33726828409755982, 0.34154312908484186]

call 0.296055783626 [0.29648125669603265, 0.29605578362613105, 0
.29716346630647195, 0.29883546651878934, 0.29798368228364236]

-- 
Gabriel Genellina




More information about the Python-list mailing list