-
-
Notifications
You must be signed in to change notification settings - Fork 11.1k
Closed
Labels
Priority: highHigh priority, also add milestones for urgent issuesHigh priority, also add milestones for urgent issuescomponent: numpy._core
Description
I have noticed that np.asarray(x)
and np.asarray(x, float)
have pretty big overheads when the input, x
, is already a float array. One could perhaps check whether that is already the case, immediately returning x
if possible. The additional check would have a negligible cost in the case where a conversion is needed (because the conversion e.g. from a x
that's a list is much slower than anything else).
Reproducing code example:
In [1]: x = np.random.rand(10, 10)
In [2]: %timeit np.asarray(x)
345 ns ± 0.53 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [3]: %timeit np.asarray(x, float)
613 ns ± 0.274 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
# Check for fast path.
In [4]: %timeit x if type(x) is np.ndarray and x.dtype == float else np.asarray(x, float)
214 ns ± 0.894 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [5]: x = np.random.rand(10, 10).tolist()
In [6]: %timeit np.asarray(x)
6.77 µs ± 6.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [7]: %timeit np.asarray(x, float)
6.78 µs ± 14.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# The additional check is a bit slower but not so much, relatively speaking.
In [8]: %timeit x if type(x) is np.ndarray and x.dtype == float else np.asarray(x, float)
6.93 µs ± 10.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Numpy/Python version information:
1.16.3 3.7.3 (default, Mar 26 2019, 21:43:19)
[GCC 8.2.1 20181127]
FirefoxMetzger
Metadata
Metadata
Assignees
Labels
Priority: highHigh priority, also add milestones for urgent issuesHigh priority, also add milestones for urgent issuescomponent: numpy._core