OPENMP的那些坑—奇偶排序
初次使用OPENMP,遇到很多坑啊。
首先
#pragma omp parallel{}
{一定要在#pragma omp parallel下方!!!例如
#pragma omp parallel
{
}
第二
#pragma omp for nowait
{
for(i.....)
}
这样的代码是不对的,会报错 OpenMP“for”指令后应为 for 循环
没错啊,下面是for啊,正确的方式是这样的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#pragma omp for nowait for (i=1; i<n-1; i=i+2) { //printf("线程ID%d\n",omp_get_thread_num()); if (a[i] > a[i+1]) { a[i] = a[i+1] + a[i]; a[i+1] = a[i] - a[i+1]; a[i] = a[i] - a[i+1]; } } } |
要紧跟着for,不能有{
串行算法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
// maopao.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "time.h" using namespace std; #define random(x) (rand()%x) int _tmain(int argc, _TCHAR* argv[]) { clock_t start, finish; double duration; int i,a[100000],j,n=100000,k,temp; for(i=0;i<n;i++){ a[i]=random(10000); } start = clock(); for(i=n-1;i>0;i--){ if(s%2==1){ //#pragma omp for nowait for (i=1; i<n-1; i=i+2) { //printf("Ïß³ÌID%d\n",omp_get_thread_num()); if (a[i] > a[i+1]) { a[i] = a[i+1] + a[i]; a[i+1] = a[i] - a[i+1]; a[i] = a[i] - a[i+1]; } } } //#pragma omp for if(s%2==0){ // #pragma omp for nowait for (i=0; i<n-1; i=i+2) { if (a[i] > a[i+1]) { a[i] = a[i+1] + a[i]; a[i+1] = a[i] - a[i+1]; a[i] = a[i] - a[i+1]; } } } } finish = clock(); duration = (double)(finish - start) / CLOCKS_PER_SEC; printf( "%f seconds\n", duration ); system("pause"); /* for(i=0;i<n;i++){ cout<<a[i]<<" "; }*/ return 0; } |
OPENMP并行算法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
// openMP1.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "time.h" #define random(x) (rand()%x) int _tmain(int argc, _TCHAR* argv[]) { clock_t start, finish; double duration; int i,a[100000],j,n=100000,k,temp,num,s; for(i=0;i<n;i++){ a[i]=random(10000); } start = clock(); //并行区域 //#pragma omp parallel num_threads(4) omp_set_num_threads(2); //printf("线程ID%d\n",omp_get_thread_num()); //#pragma omp parallel for nowait default(private) for(s=0;s<n;s++){ { #pragma omp parallel { if(s%2==1){ #pragma omp for nowait{ for (i=1; i<n-1; i=i+2) { //printf("线程ID%d\n",omp_get_thread_num()); if (a[i] > a[i+1]) { a[i] = a[i+1] + a[i]; a[i+1] = a[i] - a[i+1]; a[i] = a[i] - a[i+1]; } } } //#pragma omp for if(s%2==0){ #pragma omp for nowait for (i=0; i<n-1; i=i+2) { if (a[i] > a[i+1]) { a[i] = a[i+1] + a[i]; a[i+1] = a[i] - a[i+1]; a[i] = a[i] - a[i+1]; } } } } } } finish = clock(); duration = (double)(finish - start) / CLOCKS_PER_SEC; printf( "%f seconds\n", duration ); system("pause"); return 0; } |
飞硕蕉17
2015年10月21日 09:11
[太开心]