简体   繁体   English

Cython-为什么我的循环中的索引分配语句仍然发黄?

[英]Cython - Why is the index assignment statement inside my loop still yellow?

I am trying to learn Cython and trying to write a speedy version of a bootstrapping function. 我正在尝试学习Cython并尝试编写快速版本的自举函数。 My main loop has one pesky statement which is still yellow and I can't figure out why it's yellow. 我的主循环有一个讨厌的陈述,它仍然是黄色的,我不知道为什么它是黄色的。 I would really appreciate help, thank you. 非常感谢您的帮助。

import numpy as np
cimport numpy as np
from libc.stdlib cimport rand, RAND_MAX


ctypedef np.float64_t FLOAT_t

cpdef FLOAT_t cython_avg(np.ndarray[FLOAT_t, ndim=1] A):
    cdef double [:] x = A
    cdef double s = 0
    cdef unsigned int N = A.shape[0]
    for i in xrange(N):
        s += x[i]
    return s/N


def confidence_interval_mean(np.ndarray[FLOAT_t, ndim=1] sample,int its,int p):
    cdef int n = len(sample)
    cdef double[:] means = np.zeros(its,dtype=np.float)
    cdef np.ndarray[FLOAT_t, ndim=1] s = np.zeros(n,dtype=np.float)
    for i in xrange(its):
        for j in xrange(n):
            s[j] = sample[<int>(rand()/RAND_MAX * n)]
        means[i] = cython_avg(s)
    return np.percentile(means,[(100-p)/2,(100+p)/2])

The line which is inside the two for loops: 这两个for循环内部的行:

在两个<code> for </ code>循环内的行

Cython still generates code that checks for zero division: Cython仍会生成检查零除的代码:

if (unlikely(RAND_MAX == 0)) {
  PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero");
  {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}

and for index bounds (view BufferIndexError s being raised). 并且对于索引范围(正在引发的视图BufferIndexError )。 This code needs to raise appropriate Python exceptions if that occurs, as such, you have Python interaction. 如果发生这种情况,此代码需要引发适当的Python异常,因此,您需要进行Python交互。 The overhead from this interaction though is not something you should really be concerned about. 但是,这种交互的开销并不是您真正应该关注的事情。

If you want to get it completely white and if you are always certain the denominator != 0 and that the loop never tries to access an element that is out of bounds, you can add the appropriate compiler directives ( boundscheck and cdivision ) to eliminate these. 如果要使其完全变为白色,并且始终确定分母!= 0 ,并且循环永远不会尝试访问超出范围的元素,则可以添加适当的编译器指令boundscheckcdivision )来消除它们。

cimport them: cimport它们:

from cython cimport cdivision, boundscheck

and decorate (among other ways) your function confidence_interval_mean : 和装饰(除其他方法外)您的函数confidence_interval_mean

@cdivision
@boundscheck(False)
def confidence_interval_mean(np.ndarray[FLOAT_t, ndim=1] sample,int its,int p):
    # body stays the same

Now you get no checks and a white line: 现在您没有支票和白线:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM