[Python-Dev] Comparison speed

Greg Ball gball at cfa.harvard.edu
Fri May 18 01:18:10 CEST 2001


The timbot wrote:
> Random clue: when you're too lazy to try to subtact out loop overhead
> (not a knock, I am too), you may have better luck with
> 
>     r = [1] * 1000000
> 
> than
> 
>     r = range(1000000)
> 

This provoked me into trying my hand at a C extension.
Using CVS python, I made a new iterator that returns None some
number of times before quitting.

>>> import nones
>>> nones.new(5)
<iterator object at 0x80cfe20>
>>> for o in nones.new(5): print o
... 
None
None
None
None
None

So then I compared it to various other approaches.

>>> def loop(seq):
...     from time import clock  
...     start = clock()
...     for o in seq: pass
...     print clock()-start 
... 
>>> loop(xrange(1000000))
0.53
>>> loop(xrange(1)*1000000) 
0.52
>>> loop(range(1000000))
0.5
>>> loop(range(1)*1000000)  # same as [1]*1000000
0.43
>>> loop(nones.new(1000000)) 
0.38
>>> loop(nones.new(100000000))
38.35
>>> import sys
>>> loop(nones.new(sys.maxint)) # Not a 64 bit machine, obviously
801.52

Finally I noticed that by running python with -O I save 2 SET_LINENO
instructions per loop.

>>> loop(nones.new(100000000)) # was 38.35
26.51


> there's-as-an-art-to-doing-nothing-quickly-ly y'rs  - tim

I can now do nothing 3772000 times per second in python.  But is it really
art?

--
Greg Ball





More information about the Python-list mailing list