gpt4 book ai didi

内存 View 中扩展类型的 Cython 开销

转载 作者:行者123 更新时间:2023-12-01 04:49:34 25 4
gpt4 key购买 nike

我正在编译一个 Cython 模块,并使用 cython -a 命令检查了这段代码。

cdef INT_t print_info(Charge[:] electrons):
cdef INT_t i, index
for i in range(electrons.shape[0]):
index = electrons[i].particleindex
return index

事实证明

 + index = electrons[i].particleindex
__pyx_t_4 = __pyx_v_i;
__pyx_t_3 = (PyObject *) *((struct __pyx_obj_14particle_class_Charge * *) ( /* dim=0 */ (__pyx_v_electrons.data + __pyx_t_4 * __pyx_v_electrons.strides[0]) ));
__Pyx_INCREF((PyObject*)__pyx_t_3);
__pyx_t_5 = ((struct __pyx_obj_14particle_class_Charge *)__pyx_t_3)->particleindex;
__Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0;
__pyx_v_index = __pyx_t_5;

Charge 是一个 cdef 扩展类型,我在这里尝试使用 memoryview 缓冲区 Charge[:]。在这种情况下,Cython 似乎调用了一些 Python API,特别是生成了 __Pyx_INCREF((PyObject*)__Pyx_DECREF(((PyObject *)

我想知道是什么原因造成的,它会导致很多减速吗?这是我在论坛上的第一篇帖子,非常感谢任何意见或建议!

PS: Charge对象定义为

费用.pyx

cdef class Charge:
def __cinit__(Charge self):
self.particleindex = 0
self.charge = 0
self.mass = 0
self.energy = 0
self.on_electrode = False

收费.pxd

cdef class Charge:
cdef INT_t particleindex
cdef FLOAT_t charge
cdef FLOAT_t mass
cdef FLOAT_t energy
cdef bint on_electrode

最佳答案

Cython 可能更喜欢 pythonic 代码。重写你的函数:

cdef INT_t print_info(Charge[:] electrons):
cdef INT_t i, index
for electron in electrons:
index = electron.particleindex
return index

再试一次。

关于内存 View 中扩展类型的 Cython 开销,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34112153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com