-2
好傢伙我試圖實現與C++在這裏大矩陣相乘是代碼:C++矩陣乘法行列數
的main.cpp
#include <iostream>
#include <ctime>
#include "sauvegarder.h"
#include "restaurer.h"
using namespace std;
const int ligne = 2048;
const int colonne = 2048;
int main()
{
static float host_matrice_1[ligne][colonne];
static float host_matrice_2[ligne][colonne];
static float host_matrice_3[ligne][colonne];
clock_t sequentiel;
cudaEvent_t start, stop;
cudaEventCreate(&start);
cudaEventCreate(&stop);
//clock_t parallele;
//création des matrices avec des valeurs aléatoire
for (int i = 0; i < ligne; i++)
{
for (int j = 0; j < colonne; j++)
{
host_matrice_1[i][j] = rand() * 1000;
host_matrice_2[i][j] = rand() * 1000;
}
}
sauvegarder(host_matrice_1, "matrice_1.txt");
sauvegarder(host_matrice_2, "matrice_2.txt");
//debut de calcul de temps + multiplication
sequentiel = clock();
for (int i = 0; i < ligne; i++)
{
for (int j = 0; j < colonne; j++)
{
host_matrice_3[i][j] = 0;
for (int k = 0; k < ligne; k++)
{
host_matrice_3[i][j] = host_matrice_3[i][j] + host_matrice_1[i][k] * host_matrice_2[k][j];
}
}
}
sequentiel = clock() - sequentiel;
cout << "Temps Cpu: " << ((float)sequentiel)/CLOCKS_PER_SEC * 1000 << "ms" << endl;
sauvegarde.h
#include <iostream>
#include <fstream>
using namespace std;
const int rows = 2048;
const int cols = 2048;
void sauvegarder(static float Mat[rows][cols], string filename);
sauvegarde.cpp
#include "sauvegarder.h"
void sauvegarder(static float Mat[rows][cols], string filename)
{
ofstream output_file(filename);
for (int ligne = 0; ligne != rows; ligne++)
{
if (ligne != 0)
{
output_file << '\n';
}
for (int col = 0; col != cols; col++)
{
if (col != 0)
{
output_file << '\t';
}
output_file << Mat[ligne][col];
}
}
}
restaurer.h
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
const int ro = 2048;
const int co = 2048;
void restorer(static float mat[ro][co], string filename);
restaurer.cpp
#include "restaurer.h"
void restorer(static float mat[ro][co], string filename)
{
float x;
int row = 0;
int col = 0;
string lineA;
ifstream fileIN(filename);
//static float tmp;
while (getline(fileIN, lineA))
{
//Pour les chaines de caracteres et pas caractere.
istringstream streamA(lineA);
col = 0;
while (streamA >> x)
{
mat[row][col] = x;
col++;
}
row++;
}
}
的問題是,當我想換行和cols我需要改變它在每一個頭,甚至在main.cpp中的號碼,我怎樣才能使它從一個多變頭。
爲什麼不讓程序能夠在運行時調整行數和列數?你想有一個不同的程序,唯一的區別是行數和列數? – PaulMcKenzie
另外,你可以爲你的數組使用一點模板包裝。 'template struct Mat { Mat(){ \t \t data = new T [N]; \t \t size = N; \t}; \t int size; \t T * data; };'所以這是一維情況,但這種方法允許您設置維度並通過大小字段檢索它。 –
Christoph