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.