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

Time:11-09

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.

CodePudding user response:

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)
  • Related