Speed of str(positive_integer)..

Tony Meyer t-meyer at ihug.co.nz
Tue Jun 29 02:47:24 CEST 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
>>> t2 = timeit.Timer("a//b;a%b", "import
>>> t3 = timeit.Timer("divmod(a,b)", "import
>>> t4 = timeit.Timer("a//b;a%b", "import
>>> t.timeit()
>>> t2.timeit()
>>> t3.timeit()
>>> t4.timeit()

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