问题
How can I know whether to use def, cdef or cpdef when defining a Cython function, assuming I want optimal performance?
回答1:
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:
来源:https://stackoverflow.com/questions/49172528/should-i-define-my-cython-function-using-def-cdef-or-cpdef-for-optimal-perform