Assignment saves time?
steve at REMOVE-THIS-cybersource.com.au
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
> import timeit
> time1=timeit.Timer('s=len(li); s==1000', 'li=range(1000)')
> time2=timeit.Timer('len(li)==1000', 'li=range(1000)')
> 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 (==)
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