How can I know whether to use def, cdef or cpdef when defining a Cython function, assuming I want optimal performance?
1 Answers
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
cdefand adeffunction 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:
cpdeffunctions cause Cython to generate acdeffunction (that allows a quick function call from Cython) and adeffunction (which allows you to call it from Python). Interally thedeffunction just calls thecdeffunction.
... and from the Cython documentation:
This exploits early binding so that
cpdeffunctions may be as fast as possible when using C fundamental types (by usingcdef).cpdeffunctions use dynamic binding when passed Python objects and this might much slower, perhaps as slow asdefdeclared functions.
There exists also a case-specific benchmark (calling the function often and from Python) which yields the following result:
 
    
    - 29,336
- 6
- 55
- 86
 
    
    - 2,348
- 5
- 21
- 43
- 
                    Give this man a medal – Jotarata Aug 03 '23 at 06:46

