gpt4 book ai didi

python - Cython:对于 i 来自 1 <= i < N

转载 作者:太空狗 更新时间:2023-10-29 20:54:50 27 4
gpt4 key购买 nike

我在学习Cython并遇到了这段代码:

import numpy as np
cimport numpy as np

def mean(np.ndarray[np.double_t] input):

cdef np.double_t cur
# Py_ssize_t is numpy's index type
cdef Py_ssize_t i
cdef Py_ssize_t N = len(input)

for i from 0 <= i < N:
cur += input[i]

return cur / N

a=np.array([1,2,3,4], dtype=np.double)

显然,这会返回 a 的平均值,即 2.5。我的问题是:

for 循环是 Python 循环、Cython 还是 C?

最佳答案

编译并查看:Cython 生成的 C 代码带有很好的注释。

  /* "cyexample.pyx":11
* cdef Py_ssize_t N = len(input)
*
* for i from 0 <= i < N: # <<<<<<<<<<<<<<
* cur += input[i]
*
*/
__pyx_t_1 = __pyx_v_N;
for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_1; __pyx_v_i++) {
/* "cyexample.pyx":12
*
* for i from 0 <= i < N:
* cur += input[i] # <<<<<<<<<<<<<<
*
* return cur / N
*/
__pyx_t_2 = __pyx_v_i;
__pyx_t_3 = -1;
if (__pyx_t_2 < 0) {
__pyx_t_2 += __pyx_bshape_0_input;
if (unlikely(__pyx_t_2 < 0)) __pyx_t_3 = 0;
} else if (unlikely(__pyx_t_2 >= __pyx_bshape_0_input)) __pyx_t_3 = 0;
if (unlikely(__pyx_t_3 != -1)) {
__Pyx_RaiseBufferIndexError(__pyx_t_3);
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
__pyx_v_cur = (__pyx_v_cur + (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_double_t *, __pyx_bstruct_input.buf, __pyx_t_2, __pyx_bstride_0_input)));
}

因此循环本身成功地转换为 C。请注意,如今 Cython 可以自然地处理范围,因此不再需要旧的“from 0 <= i < N”样式。引入(非 Python)“for/from”语法的目的是表示哪些循环应该被 C 化。

关于python - Cython:对于 i 来自 1 <= i < N,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8083451/

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