Skip to content

Instantly share code, notes, and snippets.

@wangyu-
Forked from metallurgix/omp_mul.c
Created April 5, 2019 15:17
Show Gist options
  • Save wangyu-/b48a05c67dc2adb99afd9c09e2a49664 to your computer and use it in GitHub Desktop.
Save wangyu-/b48a05c67dc2adb99afd9c09e2a49664 to your computer and use it in GitHub Desktop.
Matrix Multiplication using OpenMP
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <sys/time.h>
#define N 1000
int A[N][N];
int B[N][N];
int C[N][N];
int main()
{
int i,j,k;
struct timeval tv1, tv2;
struct timezone tz;
double elapsed;
omp_set_num_threads(omp_get_num_procs());
for (i= 0; i< N; i++)
for (j= 0; j< N; j++)
{
A[i][j] = 2;
B[i][j] = 2;
}
gettimeofday(&tv1, &tz);
#pragma omp parallel for private(i,j,k) shared(A,B,C)
for (i = 0; i < N; ++i) {
for (j = 0; j < N; ++j) {
for (k = 0; k < N; ++k) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
gettimeofday(&tv2, &tz);
elapsed = (double) (tv2.tv_sec-tv1.tv_sec) + (double) (tv2.tv_usec-tv1.tv_usec) * 1.e-6;
printf("elapsed time = %f seconds.\n", elapsed);
/*for (i= 0; i< N; i++)
{
for (j= 0; j< N; j++)
{
printf("%d\t",C[i][j]);
}
printf("\n");
}*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment