I have written a small matrix multiplication program using OpenMP. I get best peroformance when I use 2 threads and worst performance when I use 1000 threads. I have total 64 processors. I get best performance when number threads in 1 or 2.
~/openmp/mat_mul> cat /proc/cpuinfo | grep processor | wc -l
64
~/openmp/mat_mul> export OMP_NUM_THREADS=2
~/openmp/mat_mul> time ./main
Total threads : 2
Master thread initializing
real 0m1.536s
user 0m2.728s
sys 0m0.200s
~/openmp/mat_mul> export OMP_NUM_THREADS=64
~/openmp/mat_mul> time ./main
Total threads : 64
Master thread initializing
real 0m25.755s
user 4m34.665s
sys 21m5.595s
This is my code for matrix multiplication.
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#define ROW_SIZE_A 100
#define COL_SIZE_A 5000
#define COL_SIZE_B 300
int get_random();
int main(int argc, char* argv[])
{
int a[ROW_SIZE_A][COL_SIZE_A];
int b[COL_SIZE_A][COL_SIZE_B];
int c[ROW_SIZE_A][COL_SIZE_B];
int i,j,k, tid, thread_cnt;
srand(time(NULL));
#pragma omp parallel shared(a,b,c,thread_cnt) private(i,j,k,tid)
{
tid = omp_get_thread_num();
if(tid == 0)
{
thread_cnt = omp_get_num_threads();
printf("Total threads : %d\n", thread_cnt);
printf("Master thread initializing\n");
}
#pragma omp parallel for schedule(static)
for(i=0; i<ROW_SIZE_A; i++)
{
for(j=0; j<COL_SIZE_A; j++)
{
a[i][j] = get_random();
}
}
#pragma omp parallel for schedule(static)
for(i=0; i<COL_SIZE_A; i++)
{
for(j=0; j<COL_SIZE_B; j++)
{
b[i][j] = get_random();
}
}
#pragma omp parallel for schedule(static)
for(i=0; i<ROW_SIZE_A; i++)
{
for(j=0; j<COL_SIZE_B; j++)
{
c[i][j] = 0;
}
}
#pragma omp barrier
#pragma omp parallel for schedule(static)
for(i=0; i<ROW_SIZE_A; i++)
{
for(j=0; j<COL_SIZE_B; j++)
{
c[i][j] = 0;
for(k=0; k<COL_SIZE_A; k++)
{
c[i][j] += a[i][k] + b[k][j];
}
}
}
}
return 0;
}
Can somebody tell me why this is happening ?