r/learnpython • • Sep 13 '26

Cython memoryviews?

I'm using a function I've compiled with cython, and I have to pass it a few very long lists. I'm pretty sure I should be using memoryviews, but do I convert the lists to memoryviews in the python part of my program or the cython part? It would be way better if I could do it in the python part because I'm passing the same lists to the function a few million times.

4 Upvotes

12 comments sorted by

View all comments

Show parent comment

1

u/BluishMontoya Sep 13 '26 edited Sep 13 '26

This becomes far more complicated if you try to use perturbation theory or the mariani-silver algorithm. Perturbation theory is basically necessary to zoom past 1 trillion times magnification, and the mariani-silver alg offers a huge speed boost. The idea is that if you can outline a rectangle, and all the points along the edge are in the mandelbrot set, then you know that everything inside the rectangle is also in the set and you don't have to do the calculations for it.

1

u/futura-bold Sep 13 '26

Oh, OK.

Regarding memoryviews, then. Generally you'd want to work with numpy arrays rather than lists as somebody's already said. Avoid accessing the individual numpy array elements within Python, though, because that's slow. You'd pass the numpy array to the cython function (which is by reference, not a copy), and the function wouldn't "convert" the array to a memoryview, as such -- it'd use the memoryview for a faster access to the memory locations within the numpy array.

If for some reason, you must access the individual array elements when setting up the arrays in pure python, then yes, you might have to set it up as a list and then convert it to a numpy array.

1

u/appu-195 Sep 20 '26

if it's about python because of Pillow I have complete replacement built in rust

you can try pillow-rs no dependency image processing using rust complete replacement for PIL -> https://github.com/appunni-m/pillow-rs

You can build your vectors directly in rust no need of conversion or numpy etc