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.

66 lines
1.9 KiB

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <iostream>
#include <ostream>
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==colB){
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_values[currentIndex]=product;
C_rowIndex[currentIndex]=rowA;
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;
int MAX;
if(A_nonZeroCount>B_nonZeroCount)MAX=A_nonZeroCount;
else MAX=B_nonZeroCount;
float C_values[MAX];
int C_rowIndex[MAX];
int C_colIndex[MAX];
int C_nonZeroCount=0;
clock_t start=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);
clock_t end=clock();
std::cout<<"基础的稀疏矩阵乘法时间:"<< double(end-start)/CLOCKS_PER_SEC<<""<<std::endl;
}