-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathexample2_numba.py
More file actions
24 lines (20 loc) · 885 Bytes
/
example2_numba.py
File metadata and controls
24 lines (20 loc) · 885 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# example2_numba.py
"""
Alternative step 2
If we can't turn our for loop into a nice list comprehension combined with a built-in function (as you can see in "example3.py"), there is another trick that we can use.
We can use the numba library that is basically a JIT compiler packed as a Python package.
It offers a @jit decorator that we can apply to our function to cut its execution time by half.
Numba works great for math heavy loops.
"""
from numba import jit # pip install numba
@jit
def compute_sum_of_powers():
total = 0
for x in range(1_000_001):
total = total + x*x
return total
total = compute_sum_of_powers()
print(total)
# It took 34.4 msec on my computer
# Just like with numpy in example5.py, benchmarks have to run twice to minimize the performance impact of the import statement
# (which shouldn't be part of the benchmark in the first place)