Numba

Basic exemple: sum elements of an array

Without Numba


In [ ]:
from numpy import arange

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

In [ ]:
a = arange(1000000).reshape(1000, 1000)

In [ ]:
%%timeit

sum2d(a)

In [ ]:
sum2d(a)

With Numba


In [ ]:
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_numba(arr):
    M, N = arr.shape
    result = 0.0
    for i in range(M):
        for j in range(N):
            result += arr[i,j]
    return result

In [ ]:
a = arange(1000000).reshape(1000, 1000)

In [ ]:
%%timeit

sum2d_numba(a)

In [ ]:
sum2d_numba(a)

Fibonacci


In [ ]:
n = 10000000

Without Numba


In [ ]:
def fibonacci(max_value):
    a, b = 0, 1
    while b < max_value:
        a, b = b, a+b
    return b

In [ ]:
%%timeit

fibonacci(n)

In [ ]:
fibonacci(n)

With Numba


In [ ]:
from numba import jit

@jit
def fibonacci_numba(max_value):
    a, b = 0, 1
    while b < max_value:
        a, b = b, a+b
    return b

In [ ]:
%%timeit

fibonacci_numba(n)

In [ ]:
fibonacci_numba(n)