如何在 Cython 中使用 `restrict` 关键字?

use*_*114 6 python cpython cython

我在 CPython 3.6 中使用 Cython,我想将一些指针标记为“无别名”,以提高性能并在语义上明确。

在 C 中,这是通过restrict( __restrict, __restrict__) 关键字完成的。但是如何使用Cython 代码中的变量restrict呢?cdef.pyx

谢谢!

ead*_*ead 7

Cython 没有 -restrict关键字的语法/支持(还?)。最好的选择是用 C 语言编写此函数,最方便的可能是使用逐字 C 代码,例如这里有一个虚拟示例:

%%cython
cdef extern from *:
    """
    void c_fun(int * CYTHON_RESTRICT a, int * CYTHON_RESTRICT b){
       a[0] = b[0];
    }
    """
    void c_fun(int *a, int *b)
    
# example usage
def doit(k):
    cdef int i=k;
    cdef int j=k+1;
    c_fun(&i,&j)
    print(i)
Run Code Online (Sandbox Code Playgroud)

这里我使用 Cython 的(未记录的)define CYTHON_RESTRICT,其定义

// restrict
#ifndef CYTHON_RESTRICT
  #if defined(__GNUC__)
    #define CYTHON_RESTRICT __restrict__
  #elif defined(_MSC_VER) && _MSC_VER >= 1400
    #define CYTHON_RESTRICT __restrict
  #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
    #define CYTHON_RESTRICT restrict
  #else
    #define CYTHON_RESTRICT
  #endif
#endif
Run Code Online (Sandbox Code Playgroud)

所以它不仅适用于 C99 兼容的 c 编译器。然而,从长远来看,最好定义类似的东西,而不是依赖于未记录的功能。