具有OpenMP任务的多线程递归fibonacci

时间:2016-04-06 22:13:43

标签: c openmp fibonacci

我知道斐波那契基本上是连续的。但我只想测试OpenMP Tasks以递归实现fibonacci系列。 C中的以下代码工作正常但我的问题是,而不是通过更多线程获得更快的结果,它变得更糟。为什么?你可以尝试自己。我想要最好的可扩展性。

使用" gcc -O3 -fopenmp -o fib fib.c"编译此代码并运行它。

#include <stdio.h>
#include <stdlib.h>
#include <omp.h>

double serialFib(int n, double* a) {
        if (n < 2) {
                a[n] = n;
                return n;
        }
        double x = serialFib(n - 1, a);
        double y = serialFib(n - 2, a);
        a[n] = x + y;
        return x + y;
}

double fib(int n, double* a) {
        if (n < 2) {
                a[n] = n;
                return n;
        }
        if (n <= 30) { // avoid task creation overhead
                return serialFib(n, a);
        }
        double x, y;
#pragma omp task shared(x, a) firstprivate(n)
        {
                x = fib(n - 1, a);
        }
#pragma omp task shared(y, a) firstprivate(n)
        {
                y = fib(n - 2, a);
        }
#pragma omp taskwait
        a[n] = x + y;
        return x + y;
}

int main(int argc, char *argv[]) {
        double t0, t1;
        // To test scalability of recursive approach
        // we take N = 40. Otherwise it will take too long.
        int N = 40, i, nthreads;

        printf("Starting benchmark...\n");
        nthreads = atoi(argv[1]);
        omp_set_num_threads(nthreads);
        double* a = (double *) calloc(N, sizeof(double));
        t0 = omp_get_wtime();

#pragma omp parallel
        {
#pragma omp single
                {
                        fib(N, a);
                }
        }

        t1 = omp_get_wtime();
        for (i = 0; i < N; ++i) {
                printf("a[%d] = %.2f\n", i, a[i]);
        }
        printf("Execution time: %f\n", t1 - t0);
        free(a);
        return 0;
}

0 个答案:

没有答案