考虑以下在 Cython 内存视图上执行就地添加的示例:
#cython: boundscheck=False, wraparound=False, initializedcheck=False, nonecheck=False, cdivision=True
from libc.stdlib cimport malloc, free
from libc.stdio cimport printf
cimport numpy as np
import numpy as np
cdef extern from "time.h":
int clock()
cdef void inplace_add(double[::1] a, double[::1] b):
cdef int i
for i in range(a.shape[0]):
a[i] += b[i]
cdef void inplace_addlocal(double[::1] a, double[::1] b):
cdef int i, n = a.shape[0]
for i in range(n):
a[i] += b[i]
def main(int N):
cdef:
int rep = 1000000, i
double* pa = <double*>malloc(N * sizeof(double))
double* pb = <double*>malloc(N * sizeof(double))
double[::1] a = <double[:N]>pa
double[::1] b = <double[:N]>pb
int start
start = clock()
for i in range(N):
a[i] = b[i] = 1. / (1 + i)
for i in range(rep):
inplace_add(a, b)
printf("loop %i\n", clock() - start)
print(np.asarray(a)[:4])
start = clock()
for i in range(N):
a[i] = b[i] = 1. / (1 + i)
for i in range(rep):
inplace_addlocal(a, b)
printf("loop_local %i\n", clock() - start)
print(np.asarray(a)[:4])
使用这些 Cython 指令,看似等效的指令inplace_add
都inplace_addlocal
可以编译为紧密的 C 循环。但是对于N=128
(我期望的近似大小inplace_addlocal
)比 快两倍(!)inplace_add
,在编译之后gcc -Ofast
(并直接编写一个采用 (int, double*, double*) 的 C 函数)或多或少与addlocal
, with or没有#openmp simd
)。传递-fopt-info
给被矢量化的gcc
节目,但不是.inplace_addlocal
inplace_add
这是 Cython 生成的 C 代码的问题(即 gcc 确实无法推断出向量化代码所需的任何保证),还是 gcc(即缺少一些优化)或其他问题?
谢谢。
(交叉发布给 cython 用户)