Skip to content

Instantly share code, notes, and snippets.

@kimdwkimdw
Created March 12, 2019 13:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kimdwkimdw/cb8ba0308f660842329b1ae7275c9362 to your computer and use it in GitHub Desktop.
Save kimdwkimdw/cb8ba0308f660842329b1ae7275c9362 to your computer and use it in GitHub Desktop.
Numba with right way
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))
@kimdwkimdw
Copy link
Author

@kimdwkimdw
Copy link
Author

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