From 136841b813aef6a0d6a8444165468f7a8ecda806 Mon Sep 17 00:00:00 2001 From: pecp45i32 Date: Fri, 29 Nov 2024 20:51:13 +0800 Subject: [PATCH] ADD file via upload --- 步骤五.cpp | 76 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 步骤五.cpp diff --git a/步骤五.cpp b/步骤五.cpp new file mode 100644 index 0000000..6d3dd0c --- /dev/null +++ b/步骤五.cpp @@ -0,0 +1,76 @@ +#include +#include +#include + +#define MAX_NONZEROS 100000 +#define MAX_SIZE 1024 + +// COO格式的稀疏矩阵结构 +typedef struct { + float values[MAX_NONZEROS]; + int rowIndex[MAX_NONZEROS]; + int colIndex[MAX_NONZEROS]; + int nonZeroCount; +} SparseMatrix; + + +void initSparseMatrix(SparseMatrix *matrix, int nonZeroCount) { + matrix->nonZeroCount = nonZeroCount; + for (int i = 0; i < nonZeroCount; i++) { + matrix->values[i] = (float)(rand() % 100) / 10.0f; + matrix->rowIndex[i] = rand() % MAX_SIZE; + matrix->colIndex[i] = rand() % MAX_SIZE; + } +} + +// 基础稀疏矩阵乘法函数 +void sparse_matmul(SparseMatrix *A, SparseMatrix *B, SparseMatrix *C) { + C->nonZeroCount = 0; + for (int i = 0; i < A->nonZeroCount; i++) { + for (int j = 0; j < B->nonZeroCount; j++) { + if (A->colIndex[i] == B->rowIndex[j]) { + int cRow = A->rowIndex[i]; + int cCol = B->colIndex[j]; + float cValue = A->values[i] * B->values[j]; + + + int k; + for (k = 0; k < C->nonZeroCount; k++) { + if (C->rowIndex[k] == cRow && C->colIndex[k] == cCol) { + C->values[k] += cValue; + break; + } + } + if (k == C->nonZeroCount) { + C->values[k] = cValue; + C->rowIndex[k] = cRow; + C->colIndex[k] = cCol; + C->nonZeroCount++; + } + } + } + } +} + +int main() { + SparseMatrix A, B, C; + + + int nonZeroCountA = 500; + int nonZeroCountB = 300; + initSparseMatrix(&A, nonZeroCountA); + initSparseMatrix(&B, nonZeroCountB); + + + clock_t start, end; + start = clock(); + + + sparse_matmul(&A, &B, &C); + + end = clock(); + double time_spent = (double)(end - start) / CLOCKS_PER_SEC; + printf("稀疏矩阵乘法的运行时间为: %lf 秒\n", time_spent); + + return 0; +} \ No newline at end of file