diff --git a/Yang/5(generate).c b/Yang/5(generate).c new file mode 100644 index 0000000..f02c642 --- /dev/null +++ b/Yang/5(generate).c @@ -0,0 +1,116 @@ +#include +#include +#include + +typedef struct { + int* values; + int* rowIndex; + int* colIndex; + int nonZeroCount; +} SparseMatrix; + +void sparseMatmul(SparseMatrix* A, SparseMatrix* B, SparseMatrix* C) { + int currentIndex = 0; + int i, j; + for (i = 0; i < A->nonZeroCount; i++) + { + int rowA = A->rowIndex[i]; + int colA = A->colIndex[i]; + float valueA = A->values[i]; + for (j = 0; j < A->nonZeroCount; j++) + { + int rowB = B->rowIndex[j]; + int colB = B->colIndex[j]; + float valueB = B->values[j]; + if (colA == rowB) + { + float product = valueA * valueB; + int found = 0; + int k; + for (k = 0; k < currentIndex; k++) + { + if (C->rowIndex[k] == rowA && C->colIndex[k] == colB){ + C->values[k] += product; + found = 1; + break; + } + } + if (!found) + { + C->values[currentIndex] = product; + C->rowIndex[currentIndex] = rowA; + C->colIndex[currentIndex] = colB; + currentIndex++; + } + } + } + } + C->nonZeroCount = currentIndex; +} + +void generate(SparseMatrix* matrix, int rows, int cols, int nonZeroCount){ + matrix->values = (int*)malloc(sizeof(int) * nonZeroCount); + matrix->rowIndex = (int*)malloc(sizeof(int) * nonZeroCount); + matrix->colIndex = (int*)malloc(sizeof(int) * nonZeroCount); + matrix->nonZeroCount = nonZeroCount; + int i; + for (i = 0; i < nonZeroCount; i++) + { + matrix->rowIndex[i] = rand() % rows; + matrix->colIndex[i] = rand() % cols; + matrix->values[i] = rand() %100; + } +} + +void free_matrix(SparseMatrix* matrix) { + free(matrix->values); + free(matrix->rowIndex); + free(matrix->colIndex); +} + +int main() { + srand(time(NULL)); + + // int i; + int rowsA = 1000; + int rowsB = 2000; + int colsB = 1000; + int nonZeroCountA = 10000; + int nonZeroCountB = 10000; + + SparseMatrix A, B; + generate(&A, rowsA, rowsB, nonZeroCountA); + generate(&B, rowsB, colsB, nonZeroCountB); + + // for (i = 0; i < A.nonZeroCount; ++i) { + // printf("A[%d][%d] = %d\n", A.rowIndex[i], A.colIndex[i], A.values[i]); + // } + + // for (i = 0; i < B.nonZeroCount; ++i) { + // printf("B[%d][%d] = %d\n", B.rowIndex[i], B.colIndex[i], B.values[i]); + // } + + + SparseMatrix C; + C.values = (int*)malloc(A.nonZeroCount * B.nonZeroCount * sizeof(int)); + C.rowIndex = (int*)malloc(A.nonZeroCount * B.nonZeroCount * sizeof(int)); + C.colIndex = (int*)malloc(A.nonZeroCount * B.nonZeroCount * sizeof(int)); + C.nonZeroCount = 0; + + clock_t start_time = clock(); + + sparseMatmul(&A, &B, &C); + + clock_t end_time = clock(); + double time = (double)(end_time - start_time) / CLOCKS_PER_SEC; + printf("%f\n", time); + + // for (i = 0; i < C.nonZeroCount; ++i) { + // printf("C[%d][%d] = %d\n", C.rowIndex[i], C.colIndex[i], C.values[i]); + // } + + free_matrix(&A); + free_matrix(&B); + free_matrix(&C); + return 0; +}