Vectorization

In [2]:
import numpy as np
In [5]:
def f(x):
    return (np.power(x,0.7))*np.sqrt(x + 1.0/np.power(np.pi,2.0))*np.sin(1.0/(x + 1.0/np.power(np.pi,2.0)))
In [7]:
f(0.1)
Out[7]:
-0.086634693531844567
In [8]:
_values=np.random.rand(10**6)
In [9]:
vect_images=f(_values)
In [19]:
list_comp_images = [ f(myX) for myX in _values ]
In [10]:
map_images=list(map(f,_values))
In [14]:
%timeit vect_images=f(_values)
3.79 ms ± 40.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [16]:
%timeit list_comp_images = [ f(myX) for myX in _values ]
683 ms ± 38.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [37]:
%timeit map_images=list(map(f,_values))
6.63 s ± 130 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [25]:
list(map(f,np.array([1,2,3])))
Out[25]:
[0.82724600833152973, 1.0788389195369004, 1.2040920195378773]
In [29]:
np.array(map(f,np.array([1,2,3])))
Out[29]:
array(<map object at 0x10a082208>, dtype=object)
In [35]:
vf=np.vectorize(f)
In [36]:
vf(_values)
Out[36]:
array([ 0.60568686,  0.82645456,  0.2556332 , ...,  0.25953504,
        0.78128834,  0.67397432])

https://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop.