-
Notifications
You must be signed in to change notification settings - Fork 0
/
fib-openmp.c
66 lines (57 loc) · 1.69 KB
/
fib-openmp.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
* fib.cpp
*
* Time how long it takes to calculate a Fibonacci number. See
* http://en.wikipedia.org/wiki/Fibonacci_number for information about the
* Fibonacci sequence. This application demonstrates the use of the cilk_spawn
* and cilk_sync keywords.
*
* This program takes a single parameter to specify the number of workers to
* be used in the calculation. If not specified, Intel Cilk Plus will query
* the operating system to determine the number of cores on the system and use
* that many workers.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <omp.h>
int fib(int n)
{
int x, y;
if (n < 2)
return n;
#pragma omp task shared(x)
x = fib(n-1);
#pragma omp task shared(y)
y = fib(n-2);
#pragma omp taskwait
return x + y;
}
int main(int argc, char *argv[])
{
// Fibonacci number to be calculated. 39 is big enough to take a
// reasonable amount of time
int n = 39;
// If we've got a parameter, assume it's the number of workers to be used
if (argc > 1)
{
// Values less than 1, or parameters that aren't numbers aren't allowed
if (atoi(argv[1]) < 1)
{
printf("Usage: fib [workers]\n");
return 1;
}
// Set the number of workers to be used
omp_set_num_threads(atoi(argv[1]));
}
// Time how long it takes to calculate the nth Fibonacci number
clock_t start = clock();
int result = fib(n);
clock_t end = clock();
// Display our results
double duration = (double)(end - start) / CLOCKS_PER_SEC;
printf("Fibonacci number #%d is %d.\n", n, result);
printf("Calculated in %.3f seconds using %d workers.\n",
duration, omp_get_num_threads());
return 0;
}