In this example, we provide a demonstration of the Numba compiler using the @guvectorize annotation.
The task to execute is matrix multiplication:
- Import guvectorize from the numba library and the numpy module:
from numba import guvectorize import numpy as np
- Using the @guvectorize decorator, we define the matmul function, which will perform the matrix multiplication task:
@guvectorize(['void(int64[:,:], int64[:,:], int64[:,:])'], '(m,n),(n,p)->(m,p)') def matmul(A, B, C): m, n = A.shape n, p = B.shape for i in range(m): for j in range(p): C[i, j] = 0 for k in range(n): C[i, j] += A[i, k] * B[k, j]
- The input matrices are 10 × 10 in size, while the elements are integers:
dim = 10 A = np.random.randint(dim,size=(dim, dim)) B = np.random.randint(dim,size=(dim, dim))
- Finally, we call the matmul function on the previously defined input matrices:
C = matmul(A, B)
- We print the input matrices and the resulting matrix:
print("INPUT MATRIX A") print(": %s" % A) print("INPUT MATRIX B") print(": %s" % B) print("RESULT MATRIX C = A*B") print(": %s" % C)