我应该使用 def、cdef 或 cpdef 定义我的 Cython 函数以获得最佳性能吗?
Should I define my Cython function using def, cdef, or cpdef for optimal performance?
假设我想要最佳性能,我如何知道在定义 Cython 函数时是使用 def、cdef 还是 cpdef?
如果你想要最佳性能,你应该知道 中提到的相关问题:
Once the function has been called there is no difference in the speed that the code inside a cdef
and a def
function runs at.
因此,为了获得最佳的 Cython 性能,您应该始终静态键入所有参数和变量,直觉上您会很想使用 cdef
,但有一些注意事项我为此构建了下面的流程图(也是基于前面提到的答案):
此外,请注意:
cpdef
functions cause Cython to generate a cdef
function (that allows a quick function call from Cython) and a def
function (which allows you to call it from Python). Interally the def
function just calls the cdef
function.
...以及来自 Cython 文档:
This exploits early binding so that cpdef
functions may be as fast as possible when using C fundamental types (by using cdef
). cpdef
functions use dynamic binding when passed Python objects and this might much slower, perhaps as slow as def
declared functions.
还有一个 case-specific benchmark(经常从 Python 调用该函数)产生以下结果:
假设我想要最佳性能,我如何知道在定义 Cython 函数时是使用 def、cdef 还是 cpdef?
如果你想要最佳性能,你应该知道
Once the function has been called there is no difference in the speed that the code inside a
cdef
and adef
function runs at.
因此,为了获得最佳的 Cython 性能,您应该始终静态键入所有参数和变量,直觉上您会很想使用 cdef
,但有一些注意事项我为此构建了下面的流程图(也是基于前面提到的答案):
此外,请注意:
cpdef
functions cause Cython to generate acdef
function (that allows a quick function call from Cython) and adef
function (which allows you to call it from Python). Interally thedef
function just calls thecdef
function.
...以及来自 Cython 文档:
This exploits early binding so that
cpdef
functions may be as fast as possible when using C fundamental types (by usingcdef
).cpdef
functions use dynamic binding when passed Python objects and this might much slower, perhaps as slow asdef
declared functions.
还有一个 case-specific benchmark(经常从 Python 调用该函数)产生以下结果: