Reputation: 783
I am trying to compare the difference between openmp reduction sum and the normal serial summation of an array. But I only got garbage number from my subroutine "fast_sum", while the result in serial_sum is correct. I am not sure why... I can compile my code successfully using gcc-7 -fopenmp. Please help me and thank you in advance!
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <omp.h>
#include <sys/time.h>
#define NUM_THREADS 8
//////// serial /////////
double serial_sum(double *A, int N){
double sum=0.0;
int i;
for(i=1;i<=N;++i)
sum += A[i];
return(sum);
}
double fast_sum(double *A, int N){
double sum=0.0;
int i;
#pragma omp parallell for reduction(+:sum) num_threads(NUM_THREADS)
for (i =1; i<=N; ++i)
sum += A[i];
return(sum);
}
int main(void)
{
int N = 256;
double sum1, sum2, sum3;
double *A;
int i, h;
A = (double*)malloc(N * sizeof(double));
for( i = 1; i<=N;++i){
A[i] = i;
}
/* initialization A[N] */
sum1 = serial_sum(A,N);
printf("normal_sum is %f\n", sum1);
sum2 = fast_sum(A,N);
printf("fast_sum is %f\n", sum2);
free(A);
}
Upvotes: 0
Views: 72
Reputation: 641
You have an indexing error here. C is 0-indexed You never initialize A[0], and you try to access A[N], even though the array is only allocated out to N-1. So who knows what values are in A[0] and A[N] - they are probably quite large, giving you the garbage value.
Upvotes: 1