Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting all elements of a numpy array to zero vs. creating a new array of zeros

Tags:

python

numpy

I'm doing a bunch of linear algebra on large matrices over and over millions of times in a while loop using numpy, at the beginning of each iteration I need the arrays to be all zeros.

Is it most efficient to reuse the existing arrays by setting all the elements to zero, ie: array[:, :, :] = 0 or to create a new array of all zeros, ie: array = np.zeros((a, b, c))

I would think that setting the elements to zero is best, but I don't know.


1 Answers

Setting a new array seems 1000 times faster on 10M cells

new array

%%timeit
a = np.zeros((1000,10000))

Output:

20.2 µs ± 1.56 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)

filling existing array

%%timeit
a[:,:] = 0

Output:

19.4 ms ± 1.77 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)
like image 88
mozway Avatar answered Sep 02 '25 06:09

mozway