2016-05-13 62 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

我認爲這是不正確的,因爲在那之後執行程序的時間必須少得多。但是,在我的代碼 –