我应该使用def,cdef还是cpdef来定义我的Cython函数以获得最佳性能? [英] Should I define my Cython function using def, cdef, or cpdef for optimal performance?
问题描述
在定义Cython函数时,如何知道是否使用def,cdef或cpdef,假设我需要最佳性能? 如果你想获得最佳性能,你应该知道,如 此外,请注意:
cpdef
函数会导致Cython生成一个cdef
函数(允许从Cython进行快速函数调用)和一个def
函数(它允许您称之为来自Python)。整数def
函数只是调用cdef
函数。
...以及来自Cython文档:
这利用了早期绑定,因此<$ c $当使用C基本类型时(通过使用
cdef
),c> cpdef 函数可能会尽可能快。当传递Python对象时,cpdef
函数使用动态绑定,这可能会慢得多,可能低于def
声明的函数。 / p>
还有一个
How can I know whether to use def, cdef or cpdef when defining a Cython function, assuming I want optimal performance?
If you want optimal performance, you should know that as mentioned in this answer to a related question:
Once the function has been called there is no difference in the speed that the code inside a
cdef
and adef
function runs at.
So for optimal Cython performance you should always statically type all arguments and variables, and intuitively you would then be tempted to use cdef
, but there are some caveats for which I constructed the flowchart below (also based on previously mentioned answer):
Furthermore, note that:
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.
... and from the Cython documentation:
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.
There exists also a case-specific benchmark in the Cython documentation (calling the function often and from Python) which yields the following result:
这篇关于我应该使用def,cdef还是cpdef来定义我的Cython函数以获得最佳性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!