SpMV的CSR程序

//CSR #include <iostream> #include <algorithm> #include <time.h> using namespace std; const int MAXM = 1500002; const int MAXN = 1500002; const int matSize = 30000000; int row, col, nnz; const int TestTime = 1; int row_start[MAXM]; int col_idx[matSize]; double value[matSize]; int row_tmp[MAXM]; double mv[MAXM]; double ret[MAXM]; typedef struct { int r,c; double val; }COO; COO mat[matSize]; bool cmp(COO a, COO b) { if (a.r == b.r) return a.c < b.c; return a.r < b.r; } void readMatrix() { FILE *fp = freopen("matrix.mtx", "r", stdin); scanf("%d%d%d", &col, &row, &nnz);//列,行,元素值 memset(mat, 0, sizeof(mat)); for (int i = 0; i < nnz; i++) { scanf("%d%d%lf", &mat[i].c, &mat[i].r, &mat[i].val); mat[i].r--; mat[i].c--; } fclose(fp); fp = freopen("matrix_b.mtx", "r", stdin); scanf("%d", &col); for (int i = 0; i < col; i++) { scanf("%lf", &mv[i]); } fclose(fp); } void convertMatrix() { for (int i = 0; i < nnz; i++) { value[i] = mat[i].val; col_idx[i] = mat[i].c; row_tmp[mat[i].r]++; } for (int i = 1; i < row + 1; i++) { row_start[i] = row_tmp[i - 1] + row_start[i - 1]; } } long mul() { memset(ret, 0, sizeof(ret)); int T = TestTime; clock_t tStart, tEnd; int s, t; tStart = clock(); while (T--) { for (int i = 0; i < row; i++) { s = row_start[i]; t = row_start[i+1]; for (int j = s; j < t; j++) { //printf("(%d, %d) ", i, col_idx[j]); ret[i] += value[j] * mv[col_idx[j]]; } //printf("/n"); } } tEnd = clock(); return tEnd - tStart; } int main() { readMatrix(); convertMatrix(); long timecost = mul(); printf("%ld/n", timecost); //freopen("csr.txt", "w", stdout); for (int i = 0; i < row; ++i) printf("%lf/n", ret[i]); //fclose(stdout); return 0; } 

你可能感兴趣的:(c,struct,File,FP,Matrix)