-
Notifications
You must be signed in to change notification settings - Fork 0
/
fib-cilk.c
63 lines (55 loc) · 1.71 KB
/
fib-cilk.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
/*
* 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 <cilk/cilk.h>
#include <cilk/cilk_api.h>
int fib(int n)
{
if (n < 2)
return n;
int x = cilk_spawn fib(n-1);
int y = fib(n-2);
cilk_sync;
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
__cilkrts_set_param("nworkers", 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, __cilkrts_get_nworkers());
return 0;
}