> > 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. -- https://mail.python.org/mailman/listinfo/python-list