通过numpy的阵列我想了解这是访问与NumPy阵列通过用Cython传递给C代码最快和最安全的方式。 我有以下文件:如何访问通过用Cython
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
,你能告诉我为什么吗?
非常感谢!
1)你告诉我! 'timeit'是你的朋友...... 2)这取决于'pyfunc'的作用(你需要修改'array'吗?你想修改它吗?)3)你能告诉我们你声明'my_array'的位置吗? –