如何用Numba加速数值计算?

进阶

答题要点

import numba
from numba import jit, njit, prange
import numpy as np

# 基本JIT
@jit(nopython=True)
def sum_array(arr):
    total = 0.0
    for i in range(len(arr)):
        total += arr[i]
    return total

# njit是nopython=True的简写
@njit
def monte_carlo_pi(n):
    inside = 0
    for _ in range(n):
        x = np.random.random()
        y = np.random.random()
        if x*x + y*y <= 1.0:
            inside += 1
    return 4.0 * inside / n

# 并行化
@njit(parallel=True)
def parallel_sum(arr):
    total = 0.0
    for i in prange(len(arr)):  # 并行循环
        total += arr[i]
    return total

# 向量化
@numba.vectorize(['float64(float64, float64)'])
def vector_add(a, b):
    return a + b

# 类型签名
@njit('float64(float64[:], float64[:])')
def dot_product(a, b):
    result = 0.0
    for i in range(len(a)):
        result += a[i] * b[i]
    return result

# CUDA GPU加速
from numba import cuda

@cuda.jit
def gpu_add(a, b, result):
    idx = cuda.grid(1)
    if idx < len(a):
        result[idx] = a[idx] + b[idx]

# 调用GPU kernel
threads_per_block = 256
blocks = (len(a) + threads_per_block - 1) // threads_per_block
gpu_add[blocks, threads_per_block](a_device, b_device, result_device)

完整解析在题库里看

核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。

去练这道题