Speed of str(positive_integer)..

Tony Meyer t-meyer at ihug.co.nz
Mon Jun 28 20:47:24 EDT 2004


> I was going to say that divmod was slower because it performs 
> float division instead of the integer division of // (which 
> is true), but I'm guessing the slowdown comes from the extra 
> dictionary lookup needed for divmod (unless this is somehow 
> optimized away) instead. If that's indeed true, then it seems 
> that divmod doesn't adequately perform its intended purpose, 
> i.e. make use of the FPU's ability to divide and modulusify 
> in one step to gain speed.

Your first guess was right.

>>> t = timeit.Timer("divmod(a,b)", "import
random;a=random.randint(-1000000,1000000);b=random.randint(-1000000,1000000)
")
>>> t2 = timeit.Timer("a//b;a%b", "import
random;a=random.randint(-1000000,1000000);b=random.randint(-1000000,1000000)
")
>>> t3 = timeit.Timer("divmod(a,b)", "import
random;a=(random.random()-0.5)*2000000;b=(random.random()-0.5)*2000000")
>>> t4 = timeit.Timer("a//b;a%b", "import
random;a=(random.random()-0.5)*2000000;b=(random.random()-0.5)*2000000")
>>> t.timeit()
0.84045206862901978
>>> t2.timeit()
0.46050238228599483
>>> t3.timeit()
1.0865115538426835
>>> t4.timeit()
1.1382552810482593

It does seem that // & % are substantially better than divmod with integers.

Floats are pretty close, really (0.05 seconds over 1 million repetitions
with Python 2.3.4 on a P4 2.4 with WinXP), with divmod just winning.

Divmod looks nicer, of course, which counts, as does (I presume) the stuff
that divmod does with signs (in floatobject.c).

=Tony Meyer





More information about the Python-list mailing list