Created
May 5, 2012 09:37
-
-
Save carl-olin/2601195 to your computer and use it in GitHub Desktop.
Recursive fibonacci with openmp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Produces correct result */ | |
#include <stdio.h> | |
long long fib(long long n) | |
{ | |
if (n < 2) { | |
return 1; | |
} | |
return fib(n - 2) + fib(n - 1); | |
} | |
int main(int argc, char ** argv) | |
{ | |
long long n = 0; | |
#pragma omp parallel for schedule(guided, 1) | |
for (n = 0; n <= 45; n++) { | |
printf("Fib(%lld): %lld\n", n, fib(n)); | |
} | |
return 0; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Data race */ | |
#include <stdio.h> | |
long long fib(long long n) | |
{ | |
if (n < 2) { | |
return 1; | |
} | |
return fib(n - 2) + fib(n - 1); | |
} | |
int main(int argc, char ** argv) | |
{ | |
long long n = 0; | |
#pragma omp parallel | |
for (n = 0; n <= 45; n++) { | |
printf("Fib(%lld): %lld\n", n, fib(n)); | |
} | |
return 0; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <omp.h> | |
#include <stdio.h> | |
long long fib(long long n) | |
{ | |
if (n < 2) { | |
return 1; | |
} | |
return fib(n - 2) + fib(n - 1); | |
} | |
/* Creates same amount of threads as number of CPUs, privatizes n, | |
and lets each thread compute threads "round robin"-style, thus | |
preventing one only thread executing the last and heaviest blocks. */ | |
int main(int argc, char ** argv) | |
{ | |
long long n = 0; | |
omp_set_num_threads(omp_get_num_procs()); | |
#pragma omp parallel private(n) | |
{ | |
#pragma omp for schedule(dynamic, 1) | |
for (n = 0; n <= 45; n++) { | |
printf("Fib(%lld): %lld\n", n, fib(n)); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment