2012-11-27 59 views
1

我有一些代碼看起來是這樣的:OpenMP的多爲循環

for(i=0; i<max;i++){ 
    for(j=0; j<max2;j++) 
    //stuff 
} 

for(i=0; i<max;i++){ 
    for(j=0; j<max2;j++) 
    //other stuff 
} 

for(i=0; i<max;i++){ 
    for(j=0; j<max2;j++) 
    //final stuff 
} 

我想這個並行使用OpenMP。什麼是最好的方法?我嘗試在開始時執行#pragma omp parallel private(i),並在每個j循環之前執行#pragma omp for。這就是我的意思:

#pragma omp parallel private(i) 
{ 
for(i=0; i<max;i++){ 
    #pragma omp for 
    for (j=0; j<max2;j++){ 
    //and so on and so forth 

事情是,這不給我任何性能提升。我懷疑這是因爲3 for循環不是並行運行的......如果我可以讓這3個運行在同一時間,我想我可以獲得性能提升。有任何想法嗎?謝謝!

+2

你的意思是,三個環路沒有數據互相依賴,使他們能夠並行運行或做你想做的每一個循環分佈在OpenMP的團隊的線程之間? –

+0

是的三個循環不是相互依賴的數據,所以我想讓它們並行運行 – pauliwago

+0

爲什麼要平行化內部循環?對於並行化來說,交給每個線程一個相當大的數據塊通常是有利的,因此除非外部循環的迭代相互依賴(所以循環'i'必須按順序執行),否則它並不真正使感覺並行化內部循環而不是外部循環。 – Grizzly

回答

2

一個快速的解決辦法是讓一個迭代的部分,該並聯:

#pragma omp for 
for (k=0;k<3;k++){ 
    if (k==0) do_stuff(); 
    if (k==1) do_other_stuff(); 
    if (k==2) do_final_stuff(); 
} 

一個更好的解決辦法是使用omp sections指令。 (從here採取的解決方案)

#pragma omp parallel sections 
{ 
    #pragma omp section 
    { 
    /* Executes in thread 1 */ 
    do_stuff(); 
    } 
    #pragma omp section 
    { 
    /* Executes in thread 2 */ 
    do_other_stuff(); 
    } 
    #pragma omp section 
    { 
    /* Executes in thread 3 */ 
    do_final_stuff(); 
    } 
} 
+0

我很少給出-1的答案,因此在你的情況下也不會這麼做,如果你自學OpenMP'sections'構造並相應地編輯你的答案。 –

+0

對不起,我不知道'omp sections'。 – banuj

+0

現在你知道了 - 任務完成了! :) –