打开应用于while循环的mp

open mp applied to while loop

本文关键字:mp 循环 while 应用于      更新时间:2023-10-16

我已经得到了以下递归代码,我正在尝试并行使用c++打开mp库。目前,我刚刚在循环之前添加了#pragma omp parallel子句(因为visual studio只支持omp 2.0,所以我不能使用任务),但它实际上减慢了速度。我做错了什么?

Ok。根据您关于使用omp节的建议,我已经重写了我的代码。现在看起来是这样的。但是,它仍然比顺序版本慢。

  long long p (long long n, long long mmm)
  {
        long long c = 0;        
        long exponent = 0;
        double ex;
        long counter = 1;
        long long ttt = 0;
        long long ttt1 = 0;
        long long b = 0;
        long long a = 0;
        long long h = 0;

        while (counter > 0)
        {
            ex = pow(-1, counter - 1);
            exponent = (long) ex;
            ttt = (n - ( (counter * ( (3 * counter) - 1)) / 2));
            ttt1 = (n - ( (counter * ( (3 * counter) + 1)) / 2));
            #pragma omp parallel sections
            {
                #pragma omp section
                {                       
                    if (ttt == 0 || ttt == 1)
                        {
                            a = exponent * 1;
                            c = c + a;
                        }
                    else if (ttt>0)
                    {                       
                         a = exponent * p((n - ( (counter * ( (3 * counter) - 1)) / 2)), mmm);
                             c = c + a;
                    }
                }

                #pragma omp section
                {
                        //If n == 1 or 0 return 1 as per convention else do the calculation
                        if (ttt1 == 0 || ttt1 == 1)
                        {
                                b = exponent * 1;
                                c = c + b;
                        }
                        else if (ttt1 > 0)
                        {
                            b = exponent * p( (n - ( (counter * ( (3 * counter) + 1)) / 2)), mmm);
                            c = c + b;
                        }
                    }
           }    
            if (ttt < 0 && ttt1 < 0)
                break;
            ++counter;
        }

#pragma omp parallel定义了一部分将并行运行的代码。这意味着你将对整个while循环进行多次并行运行,而不是对单个循环的迭代进行并行运行。

这意味着OpenMP在管理对变量的并发读/写访问方面有很大的开销,因此总运行时间更大。

如果你打算并行计算ab,你可能应该把整个if ... else if ... else标记为omp section,假设它们是完全独立的计算。

循环的自动并行化只能通过for循环和#pragma omp parallel for来实现。