[pythran] Re: dimension-independent functions?

  • From: serge Guelton <sguelton@xxxxxxxxxxxxx>
  • To: pythran@xxxxxxxxxxxxx
  • Date: Fri, 5 Sep 2014 14:18:20 +0200

On Fri, Sep 05, 2014 at 07:01:27AM -0400, Neal Becker wrote:
> What is the best way to write a dimension-independent function?  For example,
> suppose I want to apply the function &quot;sqr&quot; element-wise to an array
> of any number
> of dimensions N.
> 
> I see one way is to explicitly instantiate the function for each desired 
> number
> of dimensions:

> 
> import numpy as np
> #pythran export sqr(float64[])
> #pythran export sqr(float64[][])
> def sqr (x):
>     size = x.shape[0]
>     y = np.empty_like (x)
>     for i in range (size):
>         y[i] = x[i] * x[i]
>     return y

That's the way it should be :-/

I tried this:

    import numpy as np
    #pythran export sqr(float64[])
    #pythran export sqr(float64[][])
    #pythran export sqrv(float64[])
    #pythran export sqrv(float64[][])
    #pythran export sqr(float32[])
    #pythran export sqr(float32[][])
    #pythran export sqrv(float32[])
    #pythran export sqrv(float32[][])
    def sqr(x):
        size = x.shape[0]
        y = np.empty_like (x)
        for i in range(size):
            y[i] = x[i] * x[i]
        return y
    def sqrv(x):
        return x * x

compiled with:

pythran -DUSE_BOOST_SIMD -march=native sqr.py

and benchmarked with:

python -m timeit -s 'import numpy as np ; r =
np.asarray(np.random.rand(1000,1000), dtype=np.float64); import sqr'
'sqr.sqrv(r)'

I end up with pythran performing roughly as fast as numpy for the
vectorized version, faster when using explicit loops, and faster on
float32 thanks to vectorisation.

Other related posts: