<jupyter_start><jupyter_text>Understanding Numba* https://numba.pydata.org/<jupyter_code>from numba import njit
from numba import prange
import numpy as np

x = np.arange(100).reshape(10, 10)
def go(a):
    trace = 0
    for i in range(a.shape[0]):   
        trace += np.tanh(a[i, i]) 
    return a + trace              
@njit
def go_fast(a): # Function is compiled to machine code when called the first time
    trace = 0
    for i in range(a.shape[0]):   # Numba likes loops
        trace += np.tanh(a[i, i]) # Numba likes NumPy functions
    return a + trace              # Numba likes NumPy broadcasting
%timeit go(x)

go_fast(x) # force compilation...
%timeit go_fast(x)
def is_prime(n):
    for i in range(2,n):
        if n%i == 0 :
            return False
    return True
[i for i in range(50) if is_prime(i)]
@njit
def is_prime_fast(n):
    for i in range(2,n):
        if n%i == 0 :
            return False
    return True
[i for i in range(50) if is_prime_fast(i)]
%timeit is_prime(199999)
%timeit is_prime_fast(199999)
from numba import prange
#@njit
@njit(parallel=True)
def count_prime_fast(N):
    c = 0
    #for n in range(N) :
    for n in prange(N) :
        for i in range(2,n):
            if n%i == 0 :
                break
        else:
            c += 1
    return c
count_prime_fast(100000)
def incr(n):
    c = 0.0
    for i in range(n):
        for j in range(n):
            for k in range(n):
                c += 1.0
    return c
incr(300)
@njit
def incr_fast(n):
    c = 0.0
    for i in range(n):
        for j in range(n):
            for k in range(n):
                c += 1.0
    return c
incr_fast(300)
@njit(parallel=True)
def incr_fast_par(n):
    c = 0
    for i in prange(n):
        for j in range(n):
            for k in range(n):
                c += 1.0
    return c
incr_fast_par(300)
n = 300
%timeit incr(n)
%timeit incr_fast(n)
%timeit incr_fast_par(n)
n = 10**3
print(incr_fast(n))
print(incr_fast_par(n))

%timeit incr_fast(n)
%timeit incr_fast_par(n)<jupyter_output>1000000000.0
1000000000.0
1.06 s ± 7.46 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
81.6 ms ± 3.85 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
{'fraction_non_alphanumeric': 0.11756633119853614, 'fraction_numerical': 0.0484903934126258, 'mean_word_length': 2.24, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 2, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '83350', 'license': 'MIT', 'n_tokens_mistral': 925, 'n_tokens_neox': 842, 'n_words': 268, 'path': 'EuroSciPy-2019/5 - Thursday/06 - Understanding Numba.ipynb', 'repo_name': 'mpenagar/Irakaskuntza-Docencia-2019-2020', 'size': '2186'}