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.
86 lines
2.3 KiB
86 lines
2.3 KiB
14 hours ago
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <ctime>
|
||
|
|
||
|
#define MAX 1000
|
||
|
|
||
|
|
||
|
void sparse_matmul_coo(float* A_values, int* A_rowIndex, int* A_colIndex, int A_nonZeroCount,
|
||
|
float* B_values, int* B_rowIndex, int* B_colIndex, int B_nonZeroCount,
|
||
|
float* C_values, int* C_rowIndex, int* C_colIndex, int* C_nonZeroCount) {
|
||
|
int currentIndex = 0;
|
||
|
|
||
|
for (int i = 0; i < A_nonZeroCount; i++) {
|
||
|
int rowA = A_rowIndex[i];
|
||
|
int colA = A_colIndex[i];
|
||
|
float valueA = A_values[i];
|
||
|
|
||
|
for (int j = 0; j < B_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;
|
||
|
for (int k = 0; k < currentIndex; k++) {
|
||
|
if (C_rowIndex[k] == rowA && C_colIndex[k] == colB) {
|
||
|
C_values[k] += product;
|
||
|
found = 1;
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if (!found) {
|
||
|
C_rowIndex[currentIndex] = rowA;
|
||
|
C_values[currentIndex] = product;
|
||
|
C_colIndex[currentIndex] = colB;
|
||
|
currentIndex++;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
*C_nonZeroCount = currentIndex;
|
||
|
}
|
||
|
|
||
|
int main() {
|
||
|
|
||
|
float A_values[] = {1, 2, 3, 4, 5};
|
||
|
int A_rowIndex[] = {0, 0, 1, 2, 2};
|
||
|
int A_colIndex[] = {0, 2, 1, 0, 2};
|
||
|
int A_nonZeroCount = 5;
|
||
|
|
||
|
|
||
|
float B_values[] = {6, 8, 7, 9};
|
||
|
int B_rowIndex[] = {0, 2, 1, 2};
|
||
|
int B_colIndex[] = {0, 0, 1, 2};
|
||
|
int B_nonZeroCount = 4;
|
||
|
|
||
|
|
||
|
float C_values[MAX];
|
||
|
int C_rowIndex[MAX];
|
||
|
int C_colIndex[MAX];
|
||
|
int C_nonZeroCount = 0;
|
||
|
|
||
|
clock_t start_time, end_time;
|
||
|
|
||
|
start_time = clock();
|
||
|
|
||
|
|
||
|
sparse_matmul_coo(A_values, A_rowIndex, A_colIndex, A_nonZeroCount,
|
||
|
B_values, B_rowIndex, B_colIndex, B_nonZeroCount,
|
||
|
C_values, C_rowIndex, C_colIndex, &C_nonZeroCount);
|
||
|
|
||
|
|
||
|
end_time = clock();
|
||
|
|
||
|
|
||
|
double elapsed_time = ((double)(end_time - start_time)) / CLOCKS_PER_SEC;
|
||
|
printf("稀疏矩阵乘法的运行时间:%f 秒\n", elapsed_time);
|
||
|
|
||
|
|
||
|
|
||
|
return 0;
|
||
|
}
|