In [24]:
from numba import jit
@jit
def f(x, y):
return x + y
In [25]:
%timeit f(1, 2)
In [8]:
f(1j, 2)
Out[8]:
In [20]:
from numba import int32
@jit(int32(int32, int32))
def f1(x, y):
return x + y
In [22]:
%timeit f1(1,2)
In [14]:
f1(1j, 2)
In [23]:
%timeit f(2**32, 2**31 + 1)
In [26]:
!ping www.bbc.co.uk
In [27]:
from IPython.display import display
In [28]:
display(print)
In [31]:
import numpy as np
from numba import generated_jit, types
@ generated_jit(nopython=True)
def is_missing(x):
if isinstance(x, types.Float):
return lambda x: np.isnan(x)
elif isinstance(x, types.NPDatetime, types.NPTimedelta):
missing = x(NaT)
return lambda x: x == missing
else:
return lambda: False
In [34]:
is_missing(np.NaN)
Out[34]:
In [36]:
from numba import vectorize, float64
@vectorize([float64(float64, float64)])
def f3(x, y):
return x + y
In [38]:
f3(2.0, 3.33)
Out[38]:
In [42]:
from numba import float64, int64, float32
@vectorize([int32(int32, int32),
int64(int64, int64),
float32(float32, float32),
float64(float64, float64)])
def f(x, y):
return x + y
In [48]:
a = np.arange(6,dtype='float64')
a
Out[48]:
In [49]:
f(a,a)
Out[49]:
In [50]:
a = np.linspace(0, 1+1j, 6)
a
Out[50]:
In [51]:
f(a,a)
In [52]:
a = np.arange(12).reshape(3,4)
In [53]:
a
Out[53]:
In [54]:
f(a, a)
Out[54]:
In [55]:
f.reduce(a, axis=0) # 降维
Out[55]:
In [56]:
f.reduce(a, axis=1)
Out[56]:
In [58]:
f.accumulate(a, axis=1)
Out[58]:
In [59]:
f.accumulate(a)
Out[59]:
In [63]:
from numba import guvectorize
@guvectorize([(int64[:], int64[:], int64[:])], '(n),()->(n)', nopython=True)
def g(x, y, res):
for i in range(x.shape[0]):
res[i] = x[i] + y[0]
In [65]:
a = np.arange(6).reshape(2, 3)
g(a, 10)
Out[65]:
In [66]:
from numba import cfunc
@cfunc("float64(float64, float64)")
def add(x, y):
return x + y
In [67]:
@cfunc("float64(float64, float64)")
def add(x, y):
return x + y
print(add.ctypes(4.0, 5.0)) # prints "9.0"
In [68]:
from numba.pycc import CC
cc = CC('my_module')
# Uncomment the following line to print out the compilation steps
#cc.verbose = True
@cc.export('multf', 'f8(f8, f8)')
@cc.export('multi', 'i4(i4, i4)')
def mult(a, b):
return a * b
@cc.export('square', 'f8(f8)')
def square(a):
return a ** 2
cc.compile()
In [69]:
import my_module
my_module.multi(3, 4)
Out[69]:
In [70]:
my_module.square(1.414)
Out[70]:
In [72]:
f.inspect_types()
In [ ]: