引用Cython 文档的话:
Cython recognises the usual Python for-in-range integer loop pattern:
for i in range(n):
...
If i is declared as a cdef integer type, it will optimise this into a pure C loop
我写了一个简单的Cython函数,其中一个版本使用Python的range
,另一个版本使用for-from
Pyrex记法(它被认为是过时的):
def loop1(int start, int stop, int step):
cdef int x, t = 0
for x in range(start, stop, step):
t += x
return t
def loop2(int start, int stop, int step):
cdef int x, t = 0
for x from start <= x < stop by step:
t += x
return t
通过查看.c
文件,我注意到这两个循环被处理的方式非常不同:
第一个实际上是创建了一个Python范围,使用Python对象。并且它还包含了50行不必要的Python-to-C C-to-Python的转换代码。
第二个已经被优化为一个漂亮的纯C循环:
__pyx_t_1 = __pyx_v_stop;
__pyx_t_2 = __pyx_v_step;
for (__pyx_v_x = __pyx_v_start; __pyx_v_x < __pyx_t_1; __pyx_v_x+=__pyx_t_2) {
我是否遗漏了什么信息,还是这是一个需要我报告的bug?
unsigned int
替换int
,但结果仍然相同。而且我不知道如何告诉Cython步长的符号。 - Vincent