【发布时间】:2014-02-18 08:52:06
【问题描述】:
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
通过查看.cfile,我注意到两个循环的处理方式非常不同:
第一个实际上是使用 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) {
是我遗漏了什么还是我应该报告的错误?
【问题讨论】:
标签: python loops optimization cython