The resulting code in the first part is fast. In this article, we will compare the performance of the code with the clip()
function which is present in the NumPy library.
Surprisingly, our program is fast compared to NumPy written in C.
Code # 1: Performance comparison.
|
Output:
Time for NumPy clip program: 8.093049556000551 Time for our program:, 3.760528204000366
Well, the codes in this article required typed memory representations in Cython, which simplifies the code working with arrays. The cpdef clip ()
declaration declares clip ()
as a C and Python level function. This means that function calls are more efficiently called by other Cython functions (for example, if you want to call clip ()
from another Cython function).
The code uses two decorators & # 8212 ; @cython.boundscheck(False)
and @cython.wraparound(False)
. These are a few additional performance optimizations.
@ cython.boundscheck (False): Eliminates all bounds of the check array and will be used if indexing is not out of range.
@ cython.wraparound (False): Eliminates processing of negative array indices when going to the end of the array (as in Python lists). Including these decorators can make the code run significantly faster (almost 2.5x faster in this example in testing).
Code # 2: a variant of the clip ()
function using conditional expressions
|
After testing, this version of the code runs 50% faster. But how does this code stack up against the handwritten version of C. After some experimentation, you can verify that the handcrafted C extension is more than 10% slower than the Cython version.