Altering numpy function output array in place

2024/4/14 11:05:06

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?

Answer

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

https://en.xdnf.cn/q/72820.html

Related Q&A

Does the E-factory of lxml support dynamically generated data?

Is there a way of creating the tags dynamically with the E-factory of lxml? For instance I get a syntax error for the following code:E.BODY(E.TABLE(for row_num in range(len(ws.rows)):row = ws.rows[row…

Check if datetime object in pandas has a timezone?

Im importing data into pandas and want to remove any timezones – if theyre present in the data. If the data has a time zone, the following code works successfully: col = "my_date_column" df[…

Extract translator comments with xgettext from JavaScript (in Python mode)

I have a pretty well-working command that extracts strings from all my .js and .html files (which are just Underscore templates). However, it doesnt seem to work for Translator comments.For example, I …

Embedding python + numpy code into C++ dll callback

I am new of python embedding. I am trying to embed python + numpy code inside a C++ callback function (inside a dll)the problem i am facing is the following. if i have:Py_Initialize(); // some python g…

How to parse single file using Python bindings to Clang?

I am writing a simple tool to help with refactoring the source code of our application. I would like to parse C++ code based on wxWidgets library, which defines GUI and produce XML .ui file to use with…

How can I profile a Kivy application?

Im building a game using Kivy. Im encountering performance issues so I decided to profile the program.I tried to run it by:python -m cProfile main.pyThe application screen stays black. After several se…

Set up multiple python installations on windows with tox

I am trying to set up tox on windows to run tests against multiple python installations. I have installed each python in folders named, C:\Python\PythonXX_YY, XX is the python version (e.g. 27) and YY…

How can I change the alpha value dynamically in matplotlib python

Im seeking how to change an alpha value dynamically which are already plotted.This is a kind of sample code I want to implement, but I know it is a wrong writing.import matplotlib.pyplot as pltfig = pl…

How to detect write failure in asyncio?

As a simple example, consider the network equivalent of /dev/zero, below. (Or more realistically, just a web server sending a large file.)If a client disconnects early, you get a barrage of log message…

how to get place details from place id in google places api for python

I am using the Google Places API with Python to build a collective intelligence app for food. e.g. what restaurants are around, what ratings they have, what are their timings, etc.I am doing the follow…