| 
View
 

omp_mm.c.txt

File history uploaded by Shirley Moore 7 years, 1 month ago
/******************************************************************************
* FILE: omp_mm.c
* DESCRIPTION:  
*   OpenMp Example - Matrix Multiply - C Version
*   Demonstrates a matrix multiply using OpenMP. Threads share row iterations
*   according to a predefined chunk size.
* AUTHOR: Blaise Barney
* LAST REVISED: 06/28/05
* REVISED BY: Shirley Moore on 02/22/2017
*   Set thread scheduling using the OMP_SCHEDULE environment variable
******************************************************************************/
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>

#define NRA 2000                 /* number of rows in matrix A */
#define NCA 2000                 /* number of columns in matrix A */
#define NCB 2000                  /* number of columns in matrix B */

int main (int argc, char *argv[]) 
{
int	tid, nthreads, i, j, k;
double  starttime, endtime;
double	a[NRA][NCA],           /* matrix A to be multiplied */
	b[NCA][NCB],           /* matrix B to be multiplied */
	c[NRA][NCB];           /* result matrix C */

/*** Spawn a parallel region explicitly scoping all variables ***/
#pragma omp parallel shared(a,b,c,nthreads) private(tid,i,j,k)
  {
  tid = omp_get_thread_num();
  if (tid == 0)
    {
    nthreads = omp_get_num_threads();
    printf("Starting matrix multiply example with %d threads\n",nthreads);
    printf("Initializing matrices...\n");
    }
  /*** Initialize matrices ***/
  #pragma omp for schedule(runtime)
  for (i=0; i<NRA; i++)
    for (j=0; j<NCA; j++)
      a[i][j]= i+j;
  #pragma omp for schedule(runtime)
  for (i=0; i<NCA; i++)
    for (j=0; j<NCB; j++)
      b[i][j]= i*j;
  #pragma omp for schedule(runtime)
  for (i=0; i<NRA; i++)
    for (j=0; j<NCB; j++)
      c[i][j]= 0;

  /*** Do matrix multiply sharing iterations on outer loop ***/
  /*** Display who does which iterations for demonstration purposes ***/
//  printf("Thread %d starting matrix multiply...\n",tid);
  starttime = omp_get_wtime();
  #pragma omp for schedule(runtime) 
  for (i=0; i<NRA; i++)    
    {
//    printf("Thread=%d did row=%d\n",tid,i);
    for(j=0; j<NCB; j++)       
      for (k=0; k<NCA; k++)
        c[i][j] += a[i][k] * b[k][j];
    }
  }   /*** End of parallel region ***/

  endtime = omp_get_wtime();

/*** Print results ***/
//printf("******************************************************\n");
//printf("Result Matrix:\n");
/*for (i=0; i<NRA; i++)
  {
  for (j=0; j<NCB; j++) 
    printf("%6.2f   ", c[i][j]);
  printf("\n"); 
  }
printf("******************************************************\n");
*/
printf ("c[%d][%d] = %f\n", NRA-1, NCB-1, c[NRA-1][NCB-1]);
printf ("Execution time: %f seconds\n", endtime-starttime);

}

Comments (0)

You don't have permission to comment on this page.