Skip to content
Related Articles

Related Articles

High-Performance Array Operations with Cython | Set 1

Improve Article
Save Article
Like Article
  • Last Updated : 29 Mar, 2019

Although libraries like NumPy can perform high-performance array processing functions to operate on arrays. But Cython can also work really well. But how ?

Code #1 : Cython function for clipping the values in a simple 1D array of doubles




# work.pyx (Cython file)
cimport cython
  
@cython.boundscheck(False)
@cython.wraparound(False)
  
cpdef clip(double[:] a, double min, double max, double[:] out):
  
    '''
    Clip the values in a to be between 
    min and max. Result in out
    '''
    if min > max:
        raise ValueError("min must be <= max")
     
    if a.shape[0] != out.shape[0]:
        raise ValueError("input and output arrays must be the same size")
      
    for i in range(a.shape[0]):
        if a[i] < min:
            out[i] = min
        elif a[i] > max:
            out[i] = max
        else:
            out[i] = a[i]

 
work.py file is required to compile and build the extension.

Code #2 :




# importing libraries
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
  
ext_modules = [Extension(
        'sample'
        ['sample.pyx'])]
  
setup(name = 'Sample app'
      cmdclass = {'build_ext': build_ext}, 
      ext_modules = ext_modules)

 
After performing the task above, now we can check the working of resulting function clips arrays, with many different kinds of array objects.

Code #3 : Working of Clipping Array.




# array module example
import work
import array
import numpy
  
arr = array.array('d', [1, -3, 4, 7, 2, 0])
print ("Array : ", arr)
  
# Clipping the array
work.clip(arr, 1, 4, arr)
print ("\nClipping array : ", arr)
  
# numpy example
arr2 = numpy.random.uniform(-10, 10, size = 1000000)
print ("\narr2 : \n", arr2)
  
arr3 = numpy.zeros_like(arr2)
print ("\narr3 : \n", arr3)
  
work.clip(arr2, -5, 5, arr3)
print ("\nClipping arr3 : \n", ar3)
print ("\nMinimum in arr3 : ", min(arr3))
print ("\nMaximum in arr3 : ", min(arr3))

Output :

Array : array('d', [1.0, -3.0, 4.0, 7.0, 2.0, 0.0])

Clipping array : array('d', [1.0, 1.0, 4.0, 4.0, 2.0, 1.0])

arr2 : 
[-9.55546017, 7.45599334, 0.69248932, ..., 0.69583148, -3.86290931, 2.37266888]

arr3 : array([ 0., 0., 0., ..., 0., 0., 0.])

Clipping arr3 : 
[-5., 5., 0.69248932, ..., 0.69583148, -3.86290931, 2.37266888]

Minimum in arr3 : 5.0

Maximum in arr3 : 5.0

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!