我试图了解访问通过 Cython 传递到 C 代码的 NumPy 数组的最快 和最安全 方法是什么。 我有以下文件:
func.c:
typedef struct {
int nr;
double *my_array;
} my_struct;
my_struct grid;
void allocate(int n) {
grid.nr = n;
grid.my_array = (double*)malloc(grid.nr*sizeof(double));
}
void Cfunc1(double *array) {
my_array = array;
//e.g. operation on my_array..
for (int i=0; i<n; i++) my_array[i] *= 0.1;
}
void Cfunc2(int n, double *array) {
for (int i=0; i<n; i++) {
my_array[i] = array[i];
//e.g. operation on my_array..
for (int i=0; i<n; i++) my_array[i] *= 0.1;
}
func_wrap.pyx:
cdef extern from "func.h":
void myfunc1(double *)
void myfunc2(int, double *)
void allocate(int)
def pyfunc1(int n, double[:] array):
allocate(n)
Cfunc1(&array[0])
def pyfunc2(int n, double[:] array):
allocate(n)
Cfunc2(n, &array[0])
setup.py:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import distutils
setup(cmdclass = {'build_ext': build_ext}, ext_modules = [Extension("func", ["func.c"])])
func.so 产生于:
python setup.py build_ext --inplace
py_func.py:
import numpy
import func
arr = numpy.random.randn(10)
func.pyfunc1(arr) # or func.pyfunc2(len(arr), arr)
一些问题:
使用
Cfunc1()
还是Cfunc2()
更快?使用
Cfunc2
意味着复制数据?你会使用哪一个?理论上,我会说
Cfunc1
不需要my_array
的先前malloc
,而Cfunc2
应该需要它。相反,这两个函数似乎在没有malloc
的情况下也能正常工作,你能告诉我为什么吗?
非常感谢!
最佳答案
你的问题归结为“当我将数组传递给 C 代码时,我是否需要复制数组的内容”。答案是否定的,你不需要,但在某些情况下你可能想要。主要是当您想以某种方式修改内容而不破坏原始数组时。此外,在某些情况下,在对数据运行计算密集型算法之前将非连续数组复制到连续数组可能很有用。话虽如此,您当前的代码假定数据已经是连续的,因此在非连续的情况下,它只会给出错误的结果,复制或不复制。
如果你打算使用指针访问 numpy 数组,你几乎总是想使用 double[::1]
而不是 double[:]
这样cython 插入错误检查步骤以确保数组是连续的。
此外,如果您要将 numpy 数组的内容复制到其他数据结构(即 c 数组或 malloc 内存块)中,您需要声明/分配足够的内存才能执行此操作。如果不了解 my_array 是如何声明和分配的,就无法知道您的代码是如何工作的,但必须在某处分配内存。
关于python - 如何访问通过 Cython 传递的 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24864672/