Entering a very large number
Richard Damon
Richard at Damon-Family.org
Sun Mar 25 19:27:52 EDT 2018
On 3/25/18 8:32 AM, bartc wrote:
> On 25/03/2018 02:47, Steven D'Aprano wrote:
>> On Sun, 25 Mar 2018 00:05:56 +0100, Peter J. Holzer wrote:
>>
>> [...]
>>>> yes, good idea
>>>
>>> Not if you want to avoid that string to int conversion (as you stated).
>>>
>>> That is still there, but in addition you now split the string into a
>>> list and then join the list into a different string.
>>
>> I'm glad I wasn't the only one who spotted that.
>>
>> There's something very curious about somebody worried about efficiency
>> choosing a *less* efficient solution than what they started with. To
>> quote W.A. Wulf:
>>
>> "More computing sins are committed in the name of efficiency (without
>> necessarily achieving it) than for any other single reason — including
>> blind stupidity."
>>
>> As Donald Knuth observed:
>>
>> "We should forget about small efficiencies, say about 97% of the time:
>> premature optimization is the root of all evil."
>>
>> The Original Poster (OP) is concerned about saving, what, a tenth of a
>> microsecond in total? Hardly seems worth the effort, especially if you're
>> going to end up with something even slower.
>
> Using CPython on my machine, doing a string to int conversion that
> specific number took 200 times as long as doing a normal assignment.
>
> That conversion took 4 microseconds.
>
> Not significant if it's only done once. But it might be executed a
> million times.
>
The other half of that thought is how does the 4 microseconds to create
the constant compare to the operations USING that number. My guess is
that for most things the usage will swamp the initialization, even if
that is somewhat inefficient.
One option, which in my opinion is more readable, is if you really want
the efficency is to write the number on a single line, with a place
guide comment above, something like
# 00000000011111111112222222222333333333344444444445
# 12345678901234567890123456789012345678901234567890
foo = 13452356547242573457246245673472457723245634564564
This makes it very clear what the 47th digit of the number is (run the
guide numbers in the direction that makes sense for you)
Yes, you will have a very long line (several in fact with the guide
comment), but that 'uglyness' is worth it if the time cost turns out to
be significant. After all, correctness outweighs elegance (but maybe not
clarity, but the long line isn't unclear, just a bit ugly), so if the
time cost make the program violate the specs to be useful, you need a
bit of ugly to get it to work. (The other option would be to initialize
into a global variable, which has its own type of ugly)).
More information about the Python-list
mailing list