Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading