Created
March 12, 2019 13:10
-
-
Save kimdwkimdw/cb8ba0308f660842329b1ae7275c9362 to your computer and use it in GitHub Desktop.
Numba with right way
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import timeit | |
statements = \ | |
""" | |
import numpy as np | |
from numba import vectorize | |
def python_f(x,y): | |
if x > y: | |
m = x | |
else: | |
m = y | |
return m | |
@vectorize | |
def numba_f(x,y): | |
if x > y: | |
m = x | |
else: | |
m = y | |
return m | |
# your data, 10 million items | |
size = int(1e5) | |
x = np.random.randint(0, 20, size=size) | |
y = np.random.randint(0, 20, size=size) | |
numba_f(x,y) | |
""" | |
# pythonic way of element-wise operations | |
print(timeit.timeit('[python_f(x[i], y[i]) for i in range(len(x))]', setup=statements, number=500)) | |
# numpy has its own vectorize | |
print(timeit.timeit('numpy_f = np.vectorize(python_f)', setup=statements, number=500)) | |
# but numba's vectorize is what we're after | |
print(timeit.timeit('numba_f(x, y)', setup=statements, number=500)) |
results
- 22.113725809380412
- 0.0012139994651079178
- 0.05286153592169285
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
inspired by https://roman-kh.github.io/numba-1/