forked from pi7mcrg2k/operator_optimization
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
97 lines
2.6 KiB
97 lines
2.6 KiB
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <time.h>
|
|
|
|
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 free_matrix(SparseMatrix* matrix) {
|
|
free(matrix->values);
|
|
free(matrix->rowIndex);
|
|
free(matrix->colIndex);
|
|
}
|
|
|
|
int main() {
|
|
SparseMatrix A = {
|
|
.values = (int[]){1, 2, 3, 4, 5},
|
|
.rowIndex = (int[]){0, 0, 1, 2, 2},
|
|
.colIndex = (int[]){0, 2, 1, 0, 2},
|
|
.nonZeroCount = 5
|
|
};
|
|
|
|
SparseMatrix B = {
|
|
.values = (int[]){6, 8, 7, 9},
|
|
.rowIndex = (int[]){0, 2, 1, 2},
|
|
.colIndex = (int[]){0, 0, 1, 2},
|
|
.nonZeroCount = 4
|
|
};
|
|
|
|
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);
|
|
|
|
int i;
|
|
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;
|
|
}
|