Book Image

Mastering Python High Performance

Book Image

Mastering Python High Performance

Overview of this book

Table of Contents (15 chapters)

Numba


Numba (http://numba.pydata.org/) is a module that allows you to indicate (via decorators) to the Python interpreter which functions should be translated into machine code. Numba thus provides equivalent performance to C or Cython without the need to either use a different interpreter or actually code in C.

The module will generate optimized machine code just by requiring it. It can even be compiled to run on either CPU or GPU hardware.

Here is a very basic example taken from their official site, showing how to use it. We'll go into more detail in a bit:

from numba import jit
from numpy import arange

# jit decorator tells Numba to compile this function.
# The argument types will be inferred by Numba when function is called.
@jit
def sum2d(arr):
    M, N = arr.shape
    result = 0.0
    for i in range(M):
        for j in range(N):
            result += arr[i,j]
    return result

a = arange(9).reshape(3,3)
print(sum2d(a))

Note that even though the promise of Numba sounds impressive, the...