On 3/20/2023 11:21 AM, 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.

On my computer they all give the same result.

Python 3.10.9, PyQt version 6.4.1
Windows 10 AMD64 (build 10.0.19044) SP0
Processor: 11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz, 1690 Mhz, 4 Core(s), 8 Logical Processor(s)


sum2 evidently doesn't uses the python "big integers" e restrict the result to 
32 bits.

What about your system? Let's see if we can figure the reason for the difference.

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to