【问题标题】:warning #2901: [omp] OpenMP is not active; all OpenMP directives will be ignored警告 #2901:[omp] OpenMP 未激活;所有 OpenMP 指令都将被忽略
【发布时间】:2021-06-10 09:22:47
【问题描述】:

我目前正在尝试使用 OpenMP 进行并行计算。 我已经编写了以下基本代码。 但是它返回以下警告:

warning #2901: [omp] OpenMP is not active; all OpenMP directives will be ignored.

更改线程数不会改变所需的运行时间,因为 omp.h 由于某种我不清楚的原因被忽略了。

谁能帮帮我?

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

int main(void)
{
    double ts;
    double something;
    clock_t begin = clock();

    #pragma omp parallel num_threads(4)
    #pragma omp parallel for

    for (int i = 0; i<pow(10,7);i++)
    {
        something=sqrt(123456);
    }

    clock_t end = clock();
    ts = (double)(end - begin) / CLOCKS_PER_SEC;
    printf("Time elpased is %f seconds", ts);
}

【问题讨论】:

    标签: c++ c multithreading parallel-processing openmp


    【解决方案1】:

    除了必须使用-fopenmp 标志进行编译之外,您的代码还有一些值得指出的问题,即:

    要测量时间,请使用 omp_get_wtime() 而不是 clock()(它会为您提供所有线程中累积的时钟滴答数)。

    另一个问题是:

    #pragma omp parallel num_threads(4)
    #pragma omp parallel for
    
    for (int i = 0; i<pow(10,7);i++)
    {
        something=sqrt(123456);
    }
    

    循环的迭代没有按照您的意愿分配给线程。因为您再次将子句parallel 添加到#pragma omp for,并假设您禁用了嵌套并行性,默认情况下,在外部并行区域中创建的每个线程都将“按顺序”执行该区域内的代码.因此,对于 n = 6(即 pow(10,7) = 6)和 number of threads = 4,您将拥有以下代码块:

    for (int i=0; i<n; i++) {
       something=sqrt(123456);
    }
    

    正在执行6 x 4 = 24 次(循环迭代的总数乘以线程总数)。如需更深入的解释,请查看此SO Thread 关于类似问题。然而,下图提供了基本要素的可视化:

    要解决此问题,请将您的代码调整为以下内容:

    #pragma omp parallel for num_threads(4)
    for (int i = 0; i<pow(10,7);i++)
    {
        something=sqrt(123456);
    }
    

    【讨论】:

      【解决方案2】:

      为了获得 OpenMP 支持,您需要明确告诉您的编译器。

      • g++gccclang 需要选项 -fopenmp
      • mvsc 需要 /openmp 选项(如果您使用 Visual Studio,则需要更多信息 here

      【讨论】:

        猜你喜欢
        • 2017-06-01
        • 1970-01-01
        • 2017-09-12
        • 2021-09-07
        • 1970-01-01
        • 2020-07-15
        • 2015-03-10
        • 1970-01-01
        • 2011-08-19
        相关资源
        最近更新 更多