Performance of asarray() when input is already an array · Issue #13580 · numpy/numpy · GitHub
Skip to content

Performance of asarray() when input is already an array #13580

Description

@anntzer

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]

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions