Speed of str(positive_integer)..
Tony Meyer
t-meyer at ihug.co.nz
Mon Jun 28 20:33:29 EDT 2004
> I asked myself how much slower would be an integer-positive number to
> string convertion function against the default str().
[...]
> * It was faster for little numbers, and it seems that with
> numbers growing gets worse.
>
> *Without psyco, my native myconv is slower than str().
I suspect that the psyco version is (under the hood) doing more-or-less the
same thing as the C implementation of str() that you're testing against.
For small numbers your one beats it because you don't have to do all the
other work that str() does (negatives, non-integers, etc), but as the
numbers become larger these are less relevant and you get the expected
result of implemented-in-C just beating implemented-in-Python-plus-Psyco.
> *The thrid test is using divmod() that i thought that would
> be faster (i thought it could make only one division and get
> both qoutient and remainder, without having to multiply..)
> but was worse.
It does seem odd that "r,q = divmod(b,c)" is slower than "r = b//c;q =
b-r*c" (or "r = b//c;q=b%c", which is better), but timeit shows that it is
(with Python 2.3.4). I suppose this is the penalty for the additional work
that divmod does with checking signs and so on.
> *Also tried that function using lists instead of strings,
> but gaves worse results.
At least part of this could be due to the fact that it's quite a bit slower
(about 2x, with Python 2.3.4, here) to create an empty list than create an
empty string (which each version does, respectively).
I believe, also (and timeit seems to agree) that the append/join idiom is
only better for long strings - here there are up to 7 strings of one
character each, in which case simple += is better.
BTW, the timeit module is useful for doing these sorts of things.
=Tony Meyer
More information about the Python-list
mailing list