Prerequisite: High-Performance Array Operations with Cython | Set 1
The resulting code in the first part works fast. In this article, we will compare the performance of the code with the
clip() function that is present in the NumPy library.
As to the surprise, our program is working fast as compared to the NumPy which is written in C.
Code #1 : Comparing the performances.
Time for NumPy clip program : 8.093049556000551 Time for our program :, 3.760528204000366
Well the codes in the article required Cython typed memoryviews that simplifies the code that operates on arrays. The declaration
cpdef clip() declares
clip() as both a C-level and Python-level function. This means that the function call is more efficently called by other Cython functions (e.g., if you want to invoke
clip() from a different Cython function).
Two decorators are used in the code –
@cython.wraparound(False). Such are the few optional performance optimizations.
@cython.boundscheck(False) : Eliminates all array bounds checking and an be used if the indexing won’t go out of range.
@cython.wraparound(False) : Eliminates the handling of negative array indices as wrapping around to the end of the array (like with Python lists). The inclusion of these decorators can make the code run substantially faster (almost 2.5 times faster on this example when tested).
Code #2 : Variant of the
clip() function that uses conditional expressions
When tested, this version of the code runs over 50% faster. But how this code would stack up against a handwritten C version. After experimenting, it can be tested that a handcrafted C extension runs more than 10% slower than the version created by Cython.
- High-Performance Array Operations with Cython | Set 1
- Cython to Wrap Existing C Code
- Find the number of operations required to make all array elements Equal
- Arithmetic Operations on Images using OpenCV | Set-2 (Bitwise Operations on Binary Images)
- Operations on Python Counter
- numpy matrix operations | eye() function
- Python | Boolean List AND and OR operations
- numpy string operations | less() function
- numpy matrix operations | ones() function
- Arithmetic operations using OpenCV | Python
- numpy string operations | equal() function
- Python | Math operations for Data analysis
- numpy string operations | translate() function
- numpy string operations | greater_equal() function
- numpy string operations | less_equal() function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.