Newer
Older
Rafal Gandecki
committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// =================================================================================================
// This file is part of the CodeVault project. The project is licensed under Apache Version 2.0.
// CodeVault is part of the EU-project PRACE-4IP (WP7.3.C).
//
// Author(s):
// Rafal Gandecki <rafal.gandecki@pwr.edu.pl>
//
// This example demonstrates the use of OpenMP for matrix-matrix multiplication and
// compares execution time of algorithms.
// The example is set-up to perform single precision matrix-matrix multiplication.
// The example takes a triple input arguments (matrix A rows, matrix A cols, matric B cols),
// specifying the size of the matrices.
// See [http://www.openmp.org/] for the full OpenMP documentation.
//
// =================================================================================================
#include <omp.h>
#include <random>
#include <iostream>
void fill_random(float *A, const int &n, const int &m)
{
std::mt19937 e(static_cast<unsigned int>(time(nullptr)));
std::uniform_real_distribution<float> f;
for(int i=0; i<n; ++i)
{
for(int j=0; j<m; ++j)
{
A[i*m+j] = f(e);
}
}
}
void gemm(float *A, float *B, float *C,
const int &A_rows, const int &A_cols, const int &B_rows)
{
for(int i=0; i<A_rows; i++)
{
for(int j=0; j<B_rows; j++) {
float sum = 0.0;
for (int k=0; k<A_cols; k++) {
sum += A[i*A_cols+k] * B[k*B_rows+j];
}
C[i*B_rows+j ] = sum;
}
}
}
void gemm_OpenMP(float *A, float *B, float *C,
const int &A_rows, const int &A_cols, const int &B_rows)
{
int i, j, k;
#pragma omp parallel for shared(A, B, C, A_rows, A_cols, B_rows) private(i, j, k)
for (i = 0; i < A_rows; i++)
{
for (j = 0; j < B_rows; j++)
{
float sum = 0.0;
for (k=0; k<A_cols; k++)
{
sum += A[i*A_cols+k] * B[k*B_rows+j];
}
C[i*B_rows+j] = sum;
}
}
}
int main(int argc, char **argv)
{
int A_rows, A_cols, B_rows, B_cols;
if (argc != 4)
{
std::cout << "Usage: 3 arguments: matrix A rows, matrix A cols and matrix B cols"<< std::endl;
return 1;
}
else
{
A_rows = atoi(argv[1]);
A_cols = atoi(argv[2]);
B_rows = atoi(argv[2]);
B_cols = atoi(argv[3]);
}
double dtime;
float *A = new float[A_rows*A_cols];
float *B = new float[B_rows*B_cols];
float *C = new float[A_rows*B_cols];
fill_random(A, A_rows, A_cols);
fill_random(B, B_rows, B_cols);
dtime = omp_get_wtime();
gemm_OpenMP(A, B, C, A_rows, A_cols, B_cols);
dtime = omp_get_wtime() - dtime;
std::cout << "Time with OpenMp: " << dtime << std::endl;
dtime = omp_get_wtime();
gemm(A,B,C, A_rows, A_cols, B_cols);
dtime = omp_get_wtime() - dtime;
std::cout << "Time without OpenMP: " << dtime << std::endl;
delete[] A;
delete[] B;
delete[] C;
return 0;
}