openmp

Hi I am new and I have one question that I need to know for my next exam.

Why every program I parallelize with openmp takes a variable but however longer time than the non parallelized one?

Sorry for my english. Thank you.
Last edited on
What? "Homewhere"?
was however
Concurrent programming is a very complex subject. Not all programs can be effectively parallelized. In your case, it would seem that all the extra code OpenMP is adding is measurably more expensive than the code itself, which likely points to a blatant misuse of the directives. At the very worst, you should break even. If it's slower, it's because either you're doing something wrong, or your computer doesn't have more than one core, which means threading doesn't offer any performance advantage, which is itself doing it wrong, because properly written code is supposed to check for that.
I am new but I know I have a quad core ... not so newbie ... The parallelized program is to make factorial and another program to make power. I can post but I think it's the same everybody use.


#include <stdio.h>
#include<stdlib.h>
#include <math.h>
#include <iostream>
#include <time.h>
#include <omp.h>
using namespace std;


float x; //angolo in radianti
double app=0; //risultato approssimato
int sign=1;



double power(double, int);
double fattoriale (int);




double power (double x, int n)

{
int i; double p=1;

#pragma omp parallel for reduction(*:p)

for (i=1; i<=n; ++i)
p=p*x;

return p;
}



double fattoriale (int n)

{
double fattoriale=1;

#pragma omp parallel for reduction(*:fattoriale)


for (int i=1; i<=n; i++) fattoriale = fattoriale*i;

return fattoriale;
}





int main()
{

cout << "\nCalcolo della funzione cos x\n";

cout << "\nDi quanti radianti e' l'angolo x= ";
scanf("%f", &x);

double start_time = omp_get_wtime();

for ( int n=0 ; n < 200 ; n = n+2 )
{ app = app + sign * (power (x,n) / fattoriale (n)); sign=-sign ;}



printf("\n Il risultato finale e' cos(x)=%f \n\n", -app);

printf("\n La libreria matematica dice cos(x)=%f\n\n", cos(x));
double end_time=omp_get_wtime();
double ok_time=end_time-start_time;
cout << ok_time << endl;
return 0;
}



Last edited on
I don't know what "parallel for reduction" does, but neither power() nor fattoriale() are parallelizable. A computation can only be parallelized if some of its steps are independent. For example, matrix multiplication can be easily parallelized because the value of each element is independent from the other elements in the result matrix.

Your implementation of factorial is not parallelizable because each step requires the result of the previous step. If didn't make much sense to make it parallel, anyway. Using 32-bit ints, the result variable is overflowed after only a few iterations.
power() is unparallelizable for the same reasons.
Topic archived. No new replies allowed.