You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
np.zeros_like(a) is slower than np.zeros(shape=a.shape) #9909
I was comparing the time about two ways of an array of zeros using np.zeros_like and np.zeros.
I don't know if I'm missing something, but it seems that np.zeros_like is slower and, IMO, it seems there is no reason to be... Test has been made using an Jupyter Notebook, and is shown below:
import numpy as np; a=np.zeros(shape=(1000,1000))
%timeit -n100 np.zeros(shape=a.shape)
40.7 µs ± 5.72 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
import numpy as np; a=np.zeros(shape=(1000,1000))
%timeit -n100 np.zeros_like(a)
2.18 ms ± 47.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
This issue has been opened to suggest changing the whole implementation with
defzeros_like(a, dtype=None, order='K', subok=True):
ifnotsubok:
returnnp.zeros(shape=a.shape, dtype=dtype, order=order)
else:
res=empty_like(a, dtype=dtype, order=order, subok=subok)
# needed instead of a 0 to get same result as zeros for for string dtypesz=zeros(1, dtype=res.dtype)
multiarray.copyto(res, z, casting='unsafe')
returnres
Reacted by Tadeu Manoel, Mark Harfouche, Joshua Adelman and Muhammad Yasirroni
Activity
tarcisiofischer commentedon Oct 23, 2017
I just realised that there was a whole discussion about this in StackOverflow:
https://stackoverflow.com/questions/27464039/why-the-performance-difference-between-numpy-zeros-and-numpy-zeros-like
I can make the PR with the change, but I'll wait a bit to see if any more experienced numpy dev sees any problem with my suggestion...
tadeu commentedon Oct 24, 2017
It should also work with "array-like" objects, like lists of lists, e.g.:
but this can be accomplished with a tiny modification: using
np.shape(a)instead ofa.shape.tadeu commentedon Oct 24, 2017
dtypeandordershould also be taken froma(unless passed explicitly, in this case they would be overridden). Example:tarcisiofischer commentedon Nov 3, 2017
Thanks for the response, @tadeu. I'll take a look soon.
hmaarrfk commentedon Oct 15, 2018
I don't think your fix will address the majority of the use cases which are
where the subok parameter is never specified, but
ais not a subclassingnumpyit is is a numpy array.