python - Cython:内联函数不是纯 C

标签 python optimization inline cython

我有以下用于 Cython 的内联函数

cpdef inline int c_rate2recs_2(int maxNN,int idx):
  cdef int out=idx%maxNN
  return out

然而这转化为

/* 
 *   return out
 * 
 * cpdef inline int c_rate2recs_2(int maxNN,int idx):             # <<<<<<<<<<<<<<
 *   cdef int out=idx%maxNN
 *   return out
 */

static PyObject *__pyx_pw_6kmc_cy_5c_rate2recs_2(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static CYTHON_INLINE int __pyx_f_6kmc_cy_c_rate2recs_2(int __pyx_v_maxNN, int __pyx_v_idx, CYTHON_UNUSED int __pyx_skip_dispatch) {
  int __pyx_v_out;
  int __pyx_r;
  __Pyx_TraceDeclarations
  __Pyx_RefNannyDeclarations
  __Pyx_RefNannySetupContext("c_rate2recs_2", 0);
  __Pyx_TraceCall("c_rate2recs_2", __pyx_f[0], 984);

/* 
 *   return out
 * 
 * cpdef inline int c_rate2recs_2(int maxNN,int idx):             # <<<<<<<<<<<<<<
 *   cdef int out=idx%maxNN
 *   return out
 */

static PyObject *__pyx_pf_6kmc_cy_4c_rate2recs_2(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_maxNN, int __pyx_v_idx) {
  PyObject *__pyx_r = NULL;
  __Pyx_TraceDeclarations
  __Pyx_RefNannyDeclarations
  __Pyx_RefNannySetupContext("c_rate2recs_2", 0);
  __Pyx_TraceCall("c_rate2recs_2", __pyx_f[0], 984);
  __Pyx_XDECREF(__pyx_r);
  __pyx_t_1 = PyInt_FromLong(__pyx_f_6kmc_cy_c_rate2recs_2(__pyx_v_maxNN, __pyx_v_idx, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 984; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_GOTREF(__pyx_t_1);
  __pyx_r = __pyx_t_1;
  __pyx_t_1 = 0;
  goto __pyx_L0;

  __pyx_r = Py_None; __Pyx_INCREF(Py_None);
  goto __pyx_L0;
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_1);
  __Pyx_AddTraceback("kmc_cy.c_rate2recs_2", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = NULL;
  __pyx_L0:;
  __Pyx_XGIVEREF(__pyx_r);
  __Pyx_TraceReturn(__pyx_r);
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

由于我是 cython 业务的新手,我想知道如何摆脱大多数 Python 命令(cython -a 将此内联标记为与纯 C 相去甚远) .

最佳答案

As I am pretty new in the cython business, I would like to know how to get rid of most of the python commands (cython -a flags this inline as pretty far away from pure C)

诀窍是如果你可以调用你的函数nogil;

cpdef inline int c_rate2recs_2(int maxNN,int idx) nogil:
  cdef int out=idx%maxNN
  return out

那么无论您看到什么黄色,实际上通常都不会转到 Python。例如,它可能是一个错误案例,或者它可能只是其他类型的温和检查。在 cpdef 的情况下,不仅创建了一个纯 C 函数,还创建了一个 Python 别名以便从 Python 作用域调用。这不会影响速度。

在这种情况下,针对手动内联循环的一些计时显示没有减速,并且删除 inline 对时间也没有任何作用。我想一个更难优化的案例可能会表现出不同的特征,但关键是剖析

最后,可以通过使用 compiler directives 来加速和删除一些错误检查。 .

关于python - Cython:内联函数不是纯 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13912726/

相关文章:

python - 获取 "TypeError: unsupported operand type(s) for +: '函数'和 'function'“

python - 有没有办法使用 SpaCy 获取整个成分?

javascript - 使用 gzip 压缩 JavaScript

JQuery addClass和removeClass效率

c++ - 如何使用多重继承内联虚拟

c++ - C++ 中的宏参数求值

css - 动态加载的文本被切成两半

Python:使用列表理解生成几何级数

python - Request.data 或 Request.query_params 来访问 POST 中的参数?

java - 优化大文件的扫描仪性能