parent
b99c2d4115
commit
60bc4821e6
@ -0,0 +1,83 @@
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <time.h>
|
||||
#include <arm_neon.h>
|
||||
|
||||
#define SIZE 512
|
||||
|
||||
// 基础矩阵乘法
|
||||
void matmul(float** A, float** B, float** C, int n) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
for (int j = 0; j < n; j++) {
|
||||
C[i][j] = 0;
|
||||
for (int k = 0; k < n; k++) {
|
||||
C[i][j] += A[i][k] * B[k][j];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// NEON 优化矩阵乘法
|
||||
void matmul_optimized(float** A, float** B, float** C, int n) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
for (int j = 0; j < n; j++) {
|
||||
float32x4_t sum = vmovq_n_f32(0);
|
||||
for (int k = 0; k <= n - 4; k += 4) {
|
||||
float32x4_t vecA = vld1q_f32(&A[i][k]);
|
||||
float32x4_t vecB = vld1q_f32(&B[k][j]);
|
||||
sum = vmlaq_f32(sum, vecA, vecB);
|
||||
}
|
||||
C[i][j] = vgetq_lane_f32(sum, 0) + vgetq_lane_f32(sum, 1) +
|
||||
vgetq_lane_f32(sum, 2) + vgetq_lane_f32(sum, 3);
|
||||
for (int k = (n / 4) * 4; k < n; k++) {
|
||||
C[i][j] += A[i][k] * B[k][j];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
float** A = (float**)malloc(SIZE * sizeof(float*));
|
||||
float** B = (float**)malloc(SIZE * sizeof(float*));
|
||||
float** C = (float**)malloc(SIZE * sizeof(float*));
|
||||
|
||||
for (int i = 0; i < SIZE; i++) {
|
||||
A[i] = (float*)malloc(SIZE * sizeof(float));
|
||||
B[i] = (float*)malloc(SIZE * sizeof(float));
|
||||
C[i] = (float*)malloc(SIZE * sizeof(float));
|
||||
}
|
||||
|
||||
srand(time(NULL));
|
||||
for (int i = 0; i < SIZE; i++) {
|
||||
for (int j = 0; j < SIZE; j++) {
|
||||
A[i][j] = rand() % 100;
|
||||
B[i][j] = rand() % 100;
|
||||
}
|
||||
}
|
||||
|
||||
clock_t start, end;
|
||||
|
||||
// 基础矩阵乘法
|
||||
start = clock();
|
||||
matmul(A, B, C, SIZE);
|
||||
end = clock();
|
||||
printf("基础矩阵乘法时间: %f 秒\n", (double)(end - start) / CLOCKS_PER_SEC);
|
||||
|
||||
// NEON 优化矩阵乘法
|
||||
start = clock();
|
||||
matmul_optimized(A, B, C, SIZE);
|
||||
end = clock();
|
||||
printf("NEON 优化矩阵乘法时间: %f 秒\n", (double)(end - start) / CLOCKS_PER_SEC);
|
||||
|
||||
for (int i = 0; i < SIZE; i++) {
|
||||
free(A[i]);
|
||||
free(B[i]);
|
||||
free(C[i]);
|
||||
}
|
||||
free(A);
|
||||
free(B);
|
||||
free(C);
|
||||
|
||||
return 0;
|
||||
}
|
Loading…
Reference in new issue