Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Speed of np.empty vs np.zeros

I am using numpy version 1.14.3 and python 2.7.12.

Referencing this question, I am finding dramatically different speeds between initializing arrays with np.zeros and np.empty. However, the output is the same.

import numpy as np
r = np.random.random((50, 100, 100))
z = np.zeros(r.shape)
e = np.empty(r.shape)
np.allclose(e, z)

This returns True. However, the timing functions %timeit gives very different results:

%timeit z = np.zeros(r.shape)

10000 loops, best of 3: 143 µs per loop

%timeit e = np.empty(r.shape)

1000000 loops, best of 3: 1.83 µs per loop

The previously accepted answer referenced above says that np.zeros was always the better choice, and that it is faster too.

Why not use np.empty when it is 80 times faster than np.zeros and returns the same answer?

Edit As user2285236 pointed out, flipping the order of initializing z and e will break the equality, because it overwrites on the same memory area.

like image 686
Mike Avatar asked Sep 10 '18 16:09

Mike


People also ask

Is NumPy empty faster than zeros?

Return a new array of given shape filled with value. empty , unlike zeros , does not set the array values to zero, and may therefore be marginally faster. On the other hand, it requires the user to manually set all the values in the array, and should be used with caution.

What is the difference between the NP zeros and NP Zeros_like?

zeros obtains memory from the operating system so that the OS zeroes it when it is first used. zeros_like on the other hand fills the alloced memory with zeros by itself.

What is the point of NP empty?

This function is used to create an array without initializing the entries of given shape and type. Just like numpy. zeros(), the numpy. empty() function doesn't set the array values to zero, and it is quite faster than the numpy.

What is the use of the zeros () function in NumPy array in Python Mcq?

The zeros() function is used to get a new array of given shape and type, filled with zeros. Shape of the new array, e.g., (2, 3) or 2. The desired data-type for the array, e.g., numpy.


1 Answers

np.empty and np.zeros do different things.

np.empty creates an array from available memory space, leaving whatever values happened to be hanging around in memory as the values. These values may or may not be zeros.

np.zeros creates an array from available memory space, and then fills it with zeros for your chosen dtype. Obviously np.zeros has to do more work so it should be slower, since it's also writing to the memory allocated.

A more fair comparison would be between np.empty and np.ndarray.

like image 119
wim Avatar answered Sep 20 '22 03:09

wim