Calmcode - numba: benchmark

Benchmark

1 2 3 4 5 6

It's always a good idea to benchmark your code if you're using numba. You can also run a benchmark with extra settings.

import numpy as np
import numba as nb

@nb.njit()
def hypot_n(x, y):
    return (x**2 + y**2)**0.5

@nb.njit(parallel=True, fastmath=True)
def hypot_p(x, y):
    return (x**2 + y**2)**0.5

r1 = np.random.random(size=(2000, 2000))
r2 = np.random.random(size=(2000, 2000))

# We will call both functions once to compile them.
hypot_n(r1, r2); hypot_p(r1, r2);

You can benchmark these by running:

%timeit hypot_n(r1, r2)
%timeit (r1 ** 2 + r2 ** 2)**0.5
%timeit hypot_p(r1, r2)

Out of these, the numba function with fastmath and parallel turned on is the winner. For more information on the fastmath settings, check the docs.