You need to enable JavaScript to run this app. 基于Numba的L1缓存性能优化挑战及方案咨询
优惠活动
大模型
产品
解决方案
定价
更多

基于Numba的L1缓存性能优化挑战及方案咨询

问题描述

我正在优化NumPy数组的元素差值计算,用Numba提升性能,但当数组大小超过1MB时,耗时骤增100微秒,推测是Ryzen 7950X CPU的1MB L1缓存限制导致的。

示例代码如下:

from numba import jit
import numpy as np

@jit(nopython=True)
def extract_difference_1(random_array):
    shape0, shape1 = random_array.shape
    difference_arr = np.empty((shape0, shape1), dtype=np.float64)
    for i in range(shape0):
        difference_arr[i] = random_array[i,0] - random_array[i,1], random_array[i,1] - random_array[i,2], random_array[i,2] - random_array[i,3], random_array[i,3] - random_array[i,4], random_array[i,4] - random_array[i,5], random_array[i,5] - random_array[i,6], random_array[i,6] - random_array[i,0]

    return difference_arr

@jit(nopython=True)
def extract_difference_2(random_array):
    shape0, shape1 = random_array.shape
    split_index = shape0 // 2
    part_1 = extract_difference_1(random_array[:split_index])
    part_2 = extract_difference_1(random_array[split_index:])

    return part_1 , part_2

def array_size_string(arr):
    size_bytes = arr.nbytes
    size_kb = size_bytes / 1024
    size_mb = size_kb / 1024
    return f"{size_mb:.3f} MB, {size_kb:.2f} KB"

def timing_result_message(res):
    return f"{res.average*1e6:.1f} µs ± {res.stdev*1e6:.3f} µs,   b: {res.best*1e6:.1f} µs,    w: {res.worst*1e6:.1f} µs,     (l: {res.loops}, r: {res.runs}),"

x_list = [18500, 18700, 18900]
y = 7
for x in x_list:
    random_array = np.random.rand(x, y)
    print(f"\nFor (x,y) = ({x}, {y}), random_array size is {array_size_string(random_array)}:\n")
    for func in [extract_difference_1, extract_difference_2]:
        func(random_array) # compile the function
        timing_result = %timeit -q -o func(random_array)
        print(f"{func.__name__}:\t {timing_result_message(timing_result)}")

测试结果:

For (x,y) = (18500, 7), random_array size is 0.988 MB, 1011.72 KB:

extract_difference_1:    32.4 µs ± 832 ns,   b: 31.5 µs,    w: 34.3 µs,     (l: 7, r: 10000),
extract_difference_2:    33.8 µs ± 279 ns,   b: 33.5 µs,    w: 34.3 µs,     (l: 7, r: 10000),

For (x,y) = (18700, 7), random_array size is 0.999 MB, 1022.66 KB:

extract_difference_1:    184 µs ± 2.15 µs,   b: 181 µs,     w: 188 µs,  (l: 7, r: 10000),
extract_difference_2:    34.4 µs ± 51.2 ns,  b: 34.3 µs,    w: 34.5 µs,     (l: 7, r: 10000),

For (x,y) = (18900, 7), random_array size is 1.009 MB, 1033.59 KB:

extract_difference_1:    201 µs ± 3.3 µs,    b: 196 µs,     w: 205 µs,  (l: 7, r: 10000),
extract_difference_2:    34.5 µs ± 75.2 ns,  b: 34.4 µs,    w: 34.6 µs,     (l: 7, r: 10000),

将结果拆分为两个数组能保持性能,但我希望输出为单个数组。后续还会增大y值至10、50、100、1000,x值至20000。尝试合并拆分后的数组时,性能比extract_difference_1更差,推测是数组超过1MB无法利用L1缓存导致的。

请问是否有方法在Python、Numba或其他工具中,既能保持高性能又能输出单个数组?或者有没有办法在合并数组时避免因数组超过L1缓存而产生性能损失?


解决方案

1. 分块处理直接写入目标数组

避免先生成子数组再合并的额外开销,预先创建最终输出数组,分块处理每个缓存友好的子部分并直接写入对应位置:

@jit(nopython=True)
def extract_difference_opt(random_array):
    shape0, shape1 = random_array.shape
    difference_arr = np.empty((shape0, shape1), dtype=np.float64)
    # 设置刚好适配L1缓存的块大小(按测试的1MB临界值反推)
    chunk_size = 18500
    for start in range(0, shape0, chunk_size):
        end = min(start + chunk_size, shape0)
        chunk = random_array[start:end]
        for i in range(chunk.shape[0]):
            difference_arr[start+i] = (
                chunk[i,0] - chunk[i,1], chunk[i,1] - chunk[i,2],
                chunk[i,2] - chunk[i,3], chunk[i,3] - chunk[i,4],
                chunk[i,4] - chunk[i,5], chunk[i,5] - chunk[i,6],
                chunk[i,6] - chunk[i,0]
            )
    return difference_arr

每个块的处理都能利用L1缓存,同时直接写入最终数组,彻底消除合并步骤的性能损耗。

2. 开启Numba并行化抵消缓存延迟

利用CPU多核心并行计算,抵消数组超出L1缓存后的访问延迟:

from numba import prange

@jit(nopython=True, parallel=True)
def extract_difference_parallel(random_array):
    shape0, shape1 = random_array.shape
    difference_arr = np.empty((shape0, shape1), dtype=np.float64)
    # 并行遍历每一行,Numba自动分配任务到多个核心
    for i in prange(shape0):
        difference_arr[i] = (
            random_array[i,0] - random_array[i,1], random_array[i,1] - random_array[i,2],
            random_array[i,2] - random_array[i,3], random_array[i,3] - random_array[i,4],
            random_array[i,4] - random_array[i,5], random_array[i,5] - random_array[i,6],
            random_array[i,6] - random_array[i,0]
        )
    return difference_arr

即使数组进入L2/L3缓存,多核心并行计算也能维持接近L1缓存的性能水平。

3. 原地修改避免内存分配开销

提前分配好输出数组并传入函数,避免在函数内重复分配内存,进一步优化性能:

@jit(nopython=True)
def extract_difference_inplace(random_array, out_arr):
    shape0, shape1 = random_array.shape
    chunk_size = 18500
    for start in range(0, shape0, chunk_size):
        end = min(start + chunk_size, shape0)
        chunk = random_array[start:end]
        for i in range(chunk.shape[0]):
            out_arr[start+i] = (
                chunk[i,0] - chunk[i,1], chunk[i,1] - chunk[i,2],
                chunk[i,2] - chunk[i,3], chunk[i,3] - chunk[i,4],
                chunk[i,4] - chunk[i,5], chunk[i,5] - chunk[i,6],
                chunk[i,6] - chunk[i,0]
            )

# 使用方式
random_array = np.random.rand(20000, 1000)
out_arr = np.empty_like(random_array)
extract_difference_inplace(random_array, out_arr)

4. 用NumPy向量化操作替代循环

对于这种元素级差值计算,NumPy的向量化操作内部会利用BLAS/LAPACK优化,内存访问模式更友好,无需Numba也能获得高性能:

def extract_difference_vectorized(random_array):
    # 计算前n-1列的相邻差值
    diff = random_array[:, :-1] - random_array[:, 1:]
    # 补充最后一列与第一列的差值
    last_col = random_array[:, -1, np.newaxis] - random_array[:, 0, np.newaxis]
    return np.hstack([diff, last_col])

内容的提问来源于stack exchange,提问作者user25656250

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 03:54:52