一、矩陣加減法數學原理
1.1 定義
- ?逐元素操作:運算僅針對相同位置的元素,不涉及矩陣乘法或行列變換。
- ?交換律與結合律:
加法滿足交換律(A + B = B + A)和結合律( ( A + B ) + C = A + ( B + C ) )。
?減法不滿足交換律(A ? B ≠ B ? A)。
1.2 公式
? C i j = A i j + B i j (矩陣加法) C_{ij} = A_{ij} + B_{ij} \quad \text{(矩陣加法)} Cij?=Aij?+Bij?(矩陣加法)
C i j = A i j ? B i j (矩陣減法) C_{ij} = A_{ij} - B_{ij} \quad \text{(矩陣減法)} Cij?=Aij??Bij?(矩陣減法)
?前提條件:兩個矩陣的行列數必須相同。
二、SIMD指令集簡介
2.1 AVX2基礎
- 256位寄存器
(__m256)
,單寄存器可存儲8個float
。 - 關鍵指令:
_mm256_load_ps() // 從對齊內存加載數據到寄存器
_mm256_add_ps() // 寄存器加法
_mm256_sub_ps() // 寄存器減法
_mm256_store_ps() // 將寄存器數據存回內存
2.2 頭文件
#include <immintrin.h> // AVX指令集頭文件
三、SIMD優化矩陣加法實現
3.1 內存管理與對齊
Matrix(size_t rows, size_t cols): rows_(rows), cols_(cols),data_(static_cast<float*>(_aligned_malloc(rows* cols * sizeof(float), kSimdAlignment))) {if (!data_) throw std::bad_alloc();// 顯式初始化內存為0std::memset(data_, 0, rows * cols * sizeof(float));
}~Matrix() { _aligned_free(data_); }
- 功能:確保矩陣數據內存按32字節對齊(AVX2指令集要求)
- ?關鍵點:
a) 使用_aligned_malloc
分配對齊內存
b) 析構時通過_aligned_free
釋放內存
c) 內存不足時拋出bad_alloc
異常
3.2 二維下標訪問
class RowProxy {
public:float& operator[](size_t col) {if (col >= cols_) throw std::out_of_range("Column index out of range");return row_start_[col];}// ...
};RowProxy operator[](size_t row) {if (row >= rows_) throw std::out_of_range("Row index out of range");return RowProxy(data_ + row * cols_, cols_);
}
- 設計目標:實現類似原生二維數組的
matrix[i][j]
語法 - 實現原理:
a)operator[]
返回臨時代理對象RowProxy
b) 代理對象二次重載operator[]
實現列訪問
c) 每次訪問自動驗證行列索引合法性 - 優勢:
a) 語法直觀:mat[1][2] = 3.0f;
b) 安全性:自動邊界檢查
c) 性能:代理對象輕量(僅存儲指針和列數)
3.3 SIMD優化加減法
Matrix add_simd(const Matrix& other) const {validate_dimension(other); // 維度校驗Matrix result(rows_, cols_);// AVX指令處理主體數據(每次8個float)