16

When should I use @vectorize?

I tried @jit and show that part of the code below,

from numba import jit

@jit
def kma(g,temp): 
    k=np.exp(-(g+np.abs(g))/(2*temp))   
    return k

but my code didn't accelerate the algorithm. Why?

kinder chen
  • 1,371
  • 5
  • 15
  • 25

1 Answers1

13

@vectorize is used to write an expression that can be applied one element at a time (scalars) to an array. The @jit decorator is more general and can work on any type of calculation.

There is a detailed discussion of the other benefits in the docs:

http://numba.pydata.org/numba-doc/latest/user/vectorize.html

You might ask yourself, “why would I go through this instead of compiling a simple iteration loop using the @jit decorator?”. The answer is that NumPy ufuncs automatically get other features such as reduction, accumulation or broadcasting.

The reason why your code isn't being sped up (I see almost identical performance between jitted and non-jitted code), is that the operation you're performing is already being entirely handled by the low-level compiled code sitting behind the numpy vectorized operations.

You might get some savings if you unroll the implicit loops to avoid the creation of intermediate arrays, but typically numba really excels for operations that aren't easily vectorized in numpy.

JoshAdel
  • 66,734
  • 27
  • 141
  • 140
  • You mean the code above cannot be jitted because numpy already handled it? Numba is generally useful in 'for loops'? – kinder chen Nov 29 '17 at 22:40