【问题标题】:OpenMP actual number of threadsOpenMP 实际线程数
【发布时间】:2020-09-28 19:58:10
【问题描述】:

以下代码基于 Tim Mattson 在YouTube 上的视频教程。 我想找出调用并行时实际收到的线程数(我可能请求了 256 个线程,但最终只有 8 个)。 通常的 omp_get_num_threads() 不适用于以下内容(如果我想创建一个代码块,我会在 OpenMP 'directive' 指令错误之后得到一个预期的 for 循环):

    void pi_with_omp() {
    int i;
    double x, pi, sum = 0.0;
    double start_time, run_time;

    step = 1.0 / (double)num_steps;

    omp_set_num_threads(NUM_THREADS);
    start_time = omp_get_wtime();


    #pragma omp parallel for reduction(+:sum) private(x)
        for (i = 0; i < num_steps; i++) {
            x = (i + 0.5) * step;
            sum += 4.0 / (1.0 + x * x);
        }

    pi = step * sum;
    run_time = omp_get_wtime() - start_time;
    printf("\n pi with %ld steps is %lf in %lf seconds", num_steps, pi, run_time); 
    }

我发现的唯一方法是重写上面的 pragma 并将其分解为两个,如下所示:

    int nthreads;
    #pragma omp parallel
    {
        double x;
        int id, nthrds;
        id = omp_get_thread_num();
        nthrds = omp_get_num_threads();
        if (id == 0) nthreads = nthrds;
        #pragma omp for reduction(+:sum)
            for (i = 0; i < num_steps; i++) {
                x = (i + 0.5) * step;
                sum = sum + 4.0 / (1.0 + x * x);
            }
     }

哪个能胜任但不漂亮。有人有更好的解决方案吗?

【问题讨论】:

    标签: openmp


    【解决方案1】:

    您可以简化代码,但仍需要将parallelfor 分开。

    int nthreads;
    #pragma omp parallel 
    {  
    #pragma omp single nowait
        nthreads = omp_get_num_threads();
    #pragma omp for reduction(+:sum)
        for (i = 0; i < num_steps; i++) {
            double x = (i + 0.5) * step;
            sum = sum + 4.0 / (1.0 + x * x);
        }
    }
      
    

    【讨论】:

    • 谢谢你,我在发布问题后刚刚遇到一个命令。似乎没有办法从 for reduction 中检索线程数。如果是这样,我会接受你的回答。
    • 我意识到我应该使用single nowait;在 single 在这里构造之后你不需要屏障。
    猜你喜欢
    • 2012-09-04
    • 1970-01-01
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    相关资源
    最近更新 更多