2

I have the following code section (appropriately simplified)

cpdef double func(double[:] x, double[:] y) nogil:
    cdef:
        double[:] _y
    _y = y # Here's my trouble
    _y[2] = 2. - y[1]
    _y[1] = 1.
    return func2(x, _y)

I'm trying to create a copy of y that I can manipulate in the function. The problem is, any changes made to _y get passed back to y. I don't want to make changes to y, just to this temporary copy of it.

The function is nogil, so I can't use _y = y.copy(). (already tried). I also tried _y[:] = y, based on the cython guidance pages, but I apparently can't do that if _y hasn't been initialized yet.

So... how do I make a copy of a 1d vector without invoking the gil?

Faydey
  • 725
  • 1
  • 5
  • 12
  • 1
    Is there a good reason the function has to be `nogil`? Or that you can't use a short `with gil` block to initialize the memoryview? – DavidW Mar 27 '21 at 21:43
  • I have to do this around...125,000,000,000 times per dataset, and I have a few datasets that need to do the same thing. I'm trying to not invoke any python. – Faydey Mar 27 '21 at 22:27
  • So I tried the ```with gil``` block around ```y.copy()``` to see what kind of damage that results in, it computes func the first time, but when I try invoking it again for a different input, I get an ```UnboundLocalError: local variable '_y' referenced before assignment``` error. – Faydey Mar 27 '21 at 23:00
  • Reallocating that temporary _y array that many (billions) of times is going to be slow, regardless of the language. Are the shapes of the x and y array the same across each run? Perhaps _y can be allocated once outside of the loop that func is being called within and passed in as a parameter that is used multiple times. If that is impossible, does _y still need to exist at the end of the function after func2 is called? – CodeSurgeon Mar 28 '21 at 01:53
  • You can't. Making new memoryview objects requires the python interpreter. Try making the new view _y a parameter to be passed in. – Golden Rockefeller Apr 15 '21 at 17:18

0 Answers0