2016-05-13 91 views
4

我试图计算积分程序并行化使用OpenMP C++

#include <iostream> 
#include <omp.h> 

using namespace std; 

double my_exp(double x) { 
    double res = 1., term = 1.; 
    for(int n=1; n<=1000; n++) { 
    term *= x/n; 
    res += term; 
    } 
    return res; 
} 

double f(double x) { 
    return x*my_exp(x); 
} 


int main() { 
    double a=0., b=1., result = 0.; 
    int nsteps = 1000000; 
    double h = (b - a)/nsteps; 


    for(int i=1; i<nsteps; i++) result += f(a + i*h); 
    result = (result + .5*(f(a) + f(b)))*h; 

    cout.precision(15); 
    cout << "Result: " << result << endl; 
    return 0; 
} 

这项计划数积分和返回结果Result: 1.00000000000035 来算积分。但执行时间很多。 我应该平行我的计划,我想我应该补充#pragma omp parallel for,但它不工作

+0

我建议你使用g ++。你用'-fopenmp'编译了它吗? – muXXmit2X

+0

是的,我使用g ++。我尝试'-fopenmp',但它并不会影响执行程序的时间。我应该改变我的代码,但我从来没有使用'openmp' –

回答

1

改变你的主要功能

#pragma omp parallel 
    { 
    double localresult = 0.0; 
#pragma omp for 
    for(int i=1; i<nsteps; i++) 
     localresult += f(a + i*h); 
#pragma omp critical 
    { 
     result += localresult; 
    } 
    } 

    result = (result + .5*(f(a) + f(b)))*h; 

编辑:沿muXXmit2X的线条更简单的解决办法是

#pragma omp parallel for reduction(+:result) 
for(int i=1; i<nsteps; i++) result += f(a + i*h); 

result = (result + .5*(f(a) + f(b)))*h; 
+3

声明'reduction(+:result)'会比使用局部变量来简化操作,并且加上一个额外的步骤'critical' – Gilles

+0

True。不好的风格。我在前一篇文章中的评论中建议它现在似乎已被删除......好吧,无论如何发布...... –

+0

我认为这是不正确的,因为在那之后执行程序的时间必须少得多。但是,在我的代码 –