所以這是我的問題。我已經編寫了串行和並行的C++矩陣乘法碼。我想計算每個人執行的時間。換句話說,輸出應如下所示:C++ ctime.h不會正確計算時間
「串行乘法時間:####秒」。
「並行乘法時間:####秒」。
但我遇到的問題是在Linux機器上運行此代碼。它在Windows上完美工作,但我需要在Linux中運行此代碼。當我運行代碼時,串行乘法時間給了我一個值,但並行時間給了我更高的值,但運行速度更快。例如,我運行了一個矩陣乘法,每個矩陣乘1000x1000。串行時間爲9秒,並行時間爲18秒,但計算完成的時間很短。我等待了一段時間,串行乘法完成,但並行乘法只是在經過的時間內出現了一些錯誤的值。這裏是我的代碼:
#include <iostream>
#include <omp.h>
#include <time.h>
#include <stdlib.h>
using namespace std;
int RowA;
int ColA;
int RowB;
int ColB;
clock_t PTime = 0;
clock_t STime = 0;
double** MatA;
double** MatB;
double** MatC;
void CreateMatrix();
void PopulateMatrix();
void S_MultiplyMatrix();
void P_MultiplyMatrix();
int main()
{
cout << "Enter Size of Matrix A: ";
cin >> RowA >> ColA;
cout << "Enter size of Matrix B: ";
cin >> RowB >> ColB;
if (ColA == RowB)
{
CreateMatrix();
PopulateMatrix();
STime = clock();
S_MultiplyMatrix();
STime = clock() - STime;
cout << "Serial Matrix Multiplication time: " << STime/CLOCKS_PER_SEC << " seconds. " << endl;
PTime = clock();
P_MultiplyMatrix();
PTime = clock() - PTime;
cout << "Parallel Matrix Multiplication time: " << PTime/CLOCKS_PER_SEC << " seconds. " << endl;
}
else
{
cout << "Matrix Dimensions do not agree!!" << endl;
}
return 0;
}
void CreateMatrix()
{
MatA = new double*[RowA];
for (int i=0; i<RowA; i++)
{
MatA[i] = new double[ColA];
}
MatB = new double*[RowB];
for (int i=0; i<RowB; i++)
{
MatB[i] = new double[ColB];
}
MatC = new double*[RowA];
for (int i=0; i<RowA; i++)
{
MatC[i] = new double[ColB];
}
}
void PopulateMatrix()
{
for (int i=0; i<RowA; i++)
{
for (int j=0; j<ColA; j++)
{
MatA[i][j] = rand() & 10 + 1;
}
}
for (int i=0; i<RowB; i++)
{
for (int j=0; j<ColB; j++)
{
MatB[i][j] = rand() & 10 + 1;
}
}
}
void S_MultiplyMatrix()
{
for (int i=0; i<RowA; i++)
{
for (int j=0; j<ColB; j++)
{
for (int k=0; k<ColA; k++)
{
MatC[i][j] += MatA[i][k]*MatB[k][j];
}
}
}
}
void P_MultiplyMatrix()
{
#pragma omp parallel for //default(none) shared(MatA, MatB, MatC, RowA, ColB, ColA)
for (int i=0; i<RowA; i++)
{
#pragma omp parallel for
for (int j=0; j<ColB; j++)
{
double temp = 0;
for (int k=0; k<ColA; k++)
{
temp += MatA[i][k]*MatB[k][j];
}
MatC[i][j] = temp;
}
}
}
請幫忙解決這個問題!我不知道爲什麼它不能在Linux中正確計算時間。就像我說的,我在windows中沒有問題,但是我需要在Linux中運行它,因爲我有更大的矩陣計算需要在Linux羣集上運行,並且會準確記錄時間!
謝謝!
JD
對於初學者,您的linux編譯器是否支持OpenMP? –
18秒的CPU時間不一定意味着18秒的掛鐘時間 - 尤其是因爲您正在測量並行代碼。 –
是的,我的編譯器支持OpenMP。 – user2863626