21

What is the utility of the out parameter in certain numpy functions such as cumsum or cumprod or other mathematical functions?

If the result is huge in size does it help to use the out parameter to improve computational time or memory efficiency?

This thread gives some information about how to use it. But I want to know when should I use it and what could the benefits be?

Community
  • 1
  • 1
Sounak
  • 4,803
  • 7
  • 30
  • 48
  • 1
    Did you *read* the answers? E.g. *"Controlling the `dtype` is one reason to use `out`. Another is to conserve memory by 'reusing' an array that already exists."* – jonrsharpe Dec 04 '14 at 12:26
  • 3
    @jonrsharpe yes I did my dear. But I was looking for a bit more explanation. – Sounak Dec 04 '14 at 12:38
  • 1
    Then *mention that* in your question. What did you understand from that, and what was unclear about it? Try to *be specific* when asking questions. – jonrsharpe Dec 04 '14 at 12:39
  • @jonrsharpe can you make your comment an answer. The dtype issue is what I came to this post looking for and it isn't addressed in the other answer. – zozo Mar 18 '20 at 17:14

1 Answers1

26

Functions that take the out parameter create new objects. This is usually what you would expect from the function: Give some array and get a new one with the transformed data.

However, imagine you want to call this function several thousand times in a row. Each function call will create a new array, which of course takes a lot of time.

In this case you may want to create an output array out and let the function fill the array with the output. After processing the data you can reuse out and let the function overwrite its values. This way you won't allocate or free any memory, which can save you a lot of time.

cel
  • 30,017
  • 18
  • 97
  • 117
  • `array.cumsum(0,out=array) array.cumsum(1,out=array) array.cumsum(2,out=array) ` is better than `array.cumsum(0).cumsum(1).cumsum(2)` – Sounak Dec 04 '14 at 15:00
  • 4
    I think you should still be able to do `array.cumsum(0, out=array).cumsum(1, out=array).cumsum(2, out=array)` if you want to keep it a one-liner. – Jaime Dec 04 '14 at 15:18