Debugging reason for python running unreasonably slow when adding numbers

MRAB python at mrabarnett.plus.com
Mon Mar 20 13:42:44 EDT 2023


On 2023-03-20 15:21, Edmondo Giovannozzi wrote:
> 
>> > def sum1(): 
>> >     s = 0 
>> >     for i in range(1000000): 
>> >         s += i 
>> >     return s 
>> > 
>> > def sum2(): 
>> >     return sum(range(1000000))
>> Here you already have the numbers you want to add. 
> 
> Actually using numpy you'll be much faster in this case:
> 
> § import numpy as np
> § def sum3():
> §    return np.arange(1_000_000, dtype=np.int64).sum()
> 
> On my computer sum1 takes 44 ms, while the numpy version just 2.6 ms
> One problem is that sum2 gives the wrong result. This is why I used np.arange with dtype=np.int64.
> 
> sum2 evidently doesn't uses the python "big integers" e restrict the result to 32 bits.
> 
On my computer they all give the same result, as I'd expect.


More information about the Python-list mailing list