/******************************************************************************
* FILE: timing.c
* Author:  Amy Apon
* 
* Demonstrate the use of omp_get_wtime() to time a section of code.
******************************************************************************/
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>

#define LIMIT 100000

int main (int argc, char *argv[]) {

int nthreads, tid, i, sum=0;
double start, stop;

/* Fork a team of threads giving them their own copies of variables */
#pragma omp parallel private(nthreads,tid,i) shared(sum)
  {

  /* Obtain thread number */
  tid = omp_get_thread_num();
  nthreads = omp_get_num_threads();

  /* Only master thread does this */
  if (tid == 0) 
    {
    start = omp_get_wtime();
    printf("Number of threads = %d\n", nthreads);
    }
  /* this is protected access to a shared variable using a critical section */
    for (i=0; i<LIMIT/nthreads; i++) {
#pragma omp critical
       {
	sum++;
       }
    }
/* This barrier forces all calculations to complete before any printing */
/* That way, all threads will print the final value of sum.             */
#pragma omp barrier 
  printf("Hello World from thread = %d, sum = %d\n", tid, sum);

/* This barrier forces all printing to complete before getting the time */
/* This is not expected to be fast. */
#pragma omp barrier 
  if (tid == 0) 
    {
    stop = omp_get_wtime();
    printf("Time taken = %lf\n", stop-start);
    }

  }  /* All threads join master thread and disband */

}


