Skip to content

Instantly share code, notes, and snippets.

@clang-omp
Last active December 21, 2015 08:59
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save clang-omp/89efe59c6f79ae2bc204 to your computer and use it in GitHub Desktop.
Save clang-omp/89efe59c6f79ae2bc204 to your computer and use it in GitHub Desktop.
Openmp simple example
#include <assert.h>
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
const int N=2000;
int A[N][N], B[N][N];
int C[N][N], C1[N][N];
int main(void) {
int i, j, k;
double Start, End;
srand((int)time(NULL));
for (i = 0; i < N; ++i) {
for (j = 0; j < N; ++j) {
A[i][j] = rand() % 100;
B[i][j] = rand() % 100;
}
}
printf("---- Serial\n");
Start = omp_get_wtime();
for (i = 0; i < N; ++i) {
for (j = 0; j < N; ++j) {
int Sum = 0;
for (k = 0; k < N; ++k) {
Sum += A[i][k] * B[k][j];
}
C[i][j] = Sum;
}
}
End = omp_get_wtime();
printf("---- Serial done in %f seconds.\n", End - Start);
printf("---- Parallel\n");
Start = omp_get_wtime();
#pragma omp parallel for collapse(2)
for (i = 0; i < N; ++i) {
for (j = 0; j < N; ++j) {
int Sum = 0;
#pragma omp parallel for
for (k = 0; k < N; ++k) {
Sum += A[i][k] * B[k][j];
}
C1[i][j] = Sum;
}
}
End = omp_get_wtime();
printf("---- Parallel done in %f seconds.\n", End - Start);
printf("---- Check\n");
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
assert (C[i][j] == C1[i][j]);
}
}
printf("Passed\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment