Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Altering numpy function output array in place

I'm trying to write a function that performs a mathematical operation on an array and returns the result. A simplified example could be:

def original_func(A):
    return A[1:] + A[:-1]

For speed-up and to avoid allocating a new output array for each function call, I would like to have the output array as an argument, and alter it in place:

def inplace_func(A, out):
    out[:] = A[1:] + A[:-1]

However, when calling these two functions in the following manner,

A = numpy.random.rand(1000,1000)
out = numpy.empty((999,1000))

C = original_func(A)

inplace_func(A, out)

the original function seems to be twice as fast as the in-place function. How can this be explained? Shouldn't the in-place function be quicker since it doesn't have to allocate memory?

like image 271
halvorlu Avatar asked Sep 23 '11 13:09

halvorlu


People also ask

Can NumPy arrays be resized?

With the help of Numpy numpy. resize(), we can resize the size of an array. Array can be of any shape but to resize it we just need the size i.e (2, 2), (2, 3) and many more. During resizing numpy append zeros if values at a particular place is missing.


1 Answers

If you want to perform the operation in-place, do

def inplace_func(A, out):
    np.add(A[1:], A[:-1], out)

This does not create any temporaries (which A[1:] + A[:-1]) does.

All Numpy binary operations have corresponding functions, check the list here: http://docs.scipy.org/doc/numpy/reference/ufuncs.html#available-ufuncs

like image 173
pv. Avatar answered Sep 22 '22 23:09

pv.