我的乘法结果就像
-842150451 -842150451 -842150451 -842150451
-842150451 -842150451 -842150451 -842150451
-842150451 -84215045 -842150451 -842150451
-842150451 -84215045 -842150451 -842150451
我不明白为什么,有人可以帮忙吗?
#include <iostream>
#include <stdlib.h>
#include <omp.h>
#include <random>
using namespace std;
#define NUM_THREADS 2
double** A;
double** B;
double** C;
double t_Start;
double t_Stop;
int Am;
int An;
int Bm;
int Bn;
void Get_Matrix();
void Mat_Mult_Parallel();
int main()
{
cout << "Matrix A: ";
cin >> Am >> An;
cout << "Matrix B: ";
cin >> Bm >> Bn;
Get_Matrix();
Mat_Mult_Parallel();
system("pause");
return 0;
}
void Get_Matrix()
{
A = new double*[Am];
B = new double*[Bm];
C = new double*[Am];
for (int i = 0; i<Am; i++) { A[i] = new double[An]; }
for (int i = 0; i<Bm; i++) { B[i] = new double[Bn]; }
for (int i = 0; i<Am; i++) { C[i] = new double[Bn]; }
omp_set_num_threads(NUM_THREADS);
#pragma omp parallel for private(i,j) schedule(dynamic)
for (int i = 0; i<Am; i++)
{
for (int j = 0; j<An; j++)
{
A[i][j] = rand() % 10 +1;
cout << A[i][j] << " ";
}
cout << endl;
}
printf("\n");
#pragma omp parallel for private(i,j) schedule(dynamic)
for (int i = 0; i<Bm; i++)
{
for (int j = 0; j<Bn; j++)
{
B[i][j] = rand() % 10 + 1;
cout << B[i][j] << " ";
}
cout << endl;
}
printf("Matrix Created.\n");
}
void Mat_Mult_Parallel()
{
int i, j, k;
t_Start = omp_get_wtime();
omp_set_num_threads(NUM_THREADS);
#pragma omp parallel for private(i,j) schedule(dynamic)
for (i = 0; i<Am; i++)
{
for (j = 0; j<Bn; j++)
{
for (k = 0; k<An; k++)
{
C[i][j] += A[i][k] * B[k][j];
}
cout << C[i][j] << " ";
}
cout << endl;
}
t_Stop = omp_get_wtime() - t_Start;
cout << "Parallel: " << t_Stop << " seconds." << endl;
}
答案 0 :(得分:4)
你没有初始化你的矩阵C,但你使用'+ ='运算符,在矩阵C中为随机初始值添加值。所以你首先需要这样的东西:
for ( int i = 0; i < Am; i++ )
{
for ( int j = 0; j < Bn; j++ )
{
C[ i ][ j ] = 0.0;
}
}
或者,你可以使用memset / setmem C函数(取决于你的系统), 这可以更快。
顺便说一句,不要在并行循环中使用'cout',结果可能会令人困惑。