From 60bc4821e63a9d47df4d33e15a3ef0eca913d021 Mon Sep 17 00:00:00 2001 From: phw2xrtvn <1402919626@qq.com> Date: Sat, 23 Nov 2024 20:37:22 +0800 Subject: [PATCH] ADD file via upload --- matrix_multiplication.c | 83 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 matrix_multiplication.c diff --git a/matrix_multiplication.c b/matrix_multiplication.c new file mode 100644 index 0000000..69450aa --- /dev/null +++ b/matrix_multiplication.c @@ -0,0 +1,83 @@ + +#include +#include +#include +#include + +#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; +}