#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <pthread.h>


#define NUM_ITEMS 1000000
#define NTHREADS 4

void sum(int);

double numbers[NUM_ITEMS];
double partial_sum[NTHREADS];


int main()
{
  pthread_t thread[NTHREADS];
  int i, ret;
  double global_sum = 0;
  double time_start, time_end;
  struct timeval tv;
  struct timezone tz;

//seed random number generator
  srand(getpid());

  //fill array with random integers
  for (i = 0; i < NUM_ITEMS; i++) {
	  numbers[i] = rand();
	//   printf("%ld\n", numbers[i]);
  }

  gettimeofday(&tv, &tz);
  time_start = (double)tv.tv_sec +
    (double)tv.tv_usec / 1000000.0;

  for (i = 0; i < NUM_ITEMS; i++) {
   	global_sum += numbers[i];
  }

  gettimeofday(&tv, &tz);
  time_end = (double)tv.tv_sec +
    (double)tv.tv_usec / 1000000.0;

  printf("\nSerial Time Elapsed %lf sec.\n", time_end - time_start);


  printf("Soma Global Serie = %.1f\n", global_sum);
  global_sum = 0;

  gettimeofday(&tv, &tz);
  time_start = (double)tv.tv_sec +
    (double)tv.tv_usec / 1000000.0;

  for (i = 0; i < NTHREADS; i++) {
	 // Create thread to sum nth partition
	  ret = pthread_create(&thread[i], NULL, (void *)(&sum), (void *)i);
	  if (ret) {
	    perror("thread create");
	    exit(1);
	  }
  }
  // Wait for all threads to finish
  for (i = 0; i < NTHREADS; i++)
	  pthread_join(thread[i], NULL);

  for (i = 0; i < NTHREADS; i++)
  	global_sum += partial_sum[i];

  gettimeofday(&tv, &tz);
  time_end = (double)tv.tv_sec +
    (double)tv.tv_usec / 1000000.0;

  printf("\nParalell Time Elapsed %lf sec.\n", time_end - time_start);

  printf("Soma Global Paralelo = %.1f\n", global_sum);
}

void sum(int order)
{
 double local_sum = 0;
 int i;

 int begin = NUM_ITEMS/NTHREADS * order;
 int end = NUM_ITEMS/NTHREADS * (order + 1);

  for (i = begin; i < end; i++) {
  	local_sum += numbers[i];
  }
  partial_sum[order] = local_sum;
}
