openmp 并行求完数
// GetWanShu.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "omp.h" #include <Windows.h> #include "time.h" //函数声明 void getWanShuBySection(); void getWanShu(); void getWanShuByReduction(); int _tmain(int argc, _TCHAR* argv[]) { //串行实现求完数 clock_t start_LiXingLe=clock(); getWanShu(); clock_t end_LiXingLe=clock(); double chuanxingTime_LXL=end_LiXingLe-start_LiXingLe; printf(" 串行时间为:%f\n",chuanxingTime_LXL); //section 并行方法实现 getWanShuBySection(); //Reduction 并行方法实现 getWanShuByReduction(); //for 并行方法实现 omp_set_num_threads(4); start_LiXingLe=clock(); #pragma omp parallel #pragma omp for for (int n = 1; n <= 10000; n++) { int sum = 0; for (int i = 1; i <= (n/2); i++) //除到原来一半就可以了 { if (n % i == 0) { sum += i; } } if (sum == n) { printf ("%d\n", sum); } } end_LiXingLe=clock(); double parallelTime_LXL=end_LiXingLe-start_LiXingLe; printf(" for并行时间为 :%f\n",parallelTime_LXL); printf("for加速比为:%f\n",chuanxingTime_LXL/ parallelTime_LXL); return 0; } void getWanShuBySection(){ omp_set_num_threads(4); clock_t start_LiXingLe=clock(); #pragma omp parallel { #pragma omp sections { #pragma omp section for (int n = 1; n < 2500; n++) { int sum = 0; for (int i = 1; i <= (n/2); i++) //除到原来一半就可以了 { if (n % i == 0) { sum += i; } } if (sum == n) { printf ("%d\n", sum); } } #pragma omp section for (int n = 2500; n < 5000; n++) { int sum = 0; for (int i = 1; i <= (n/2); i++) //除到原来一半就可以了 { if (n % i == 0) { sum += i; } } if (sum == n) { printf ("%d\n", sum); } } #pragma omp section for (int n = 5000; n <= 7500; n++) { int sum = 0; for (int i = 1; i <= (n/2); i++) //除到原来一半就可以了 { if (n % i == 0) { sum += i; } } if (sum == n) { printf ("%d\n", sum); } } #pragma omp section for (int n = 7500; n <= 10000; n++) { int sum = 0; for (int i = 1; i <= (n/2); i++) //除到原来一半就可以了 { if (n % i == 0) { sum += i; } } if (sum == n) { printf ("%d\n", sum); } } } } clock_t end_LiXingLe=clock(); printf(" section并行时间为 :%d\n",end_LiXingLe-start_LiXingLe); } void getWanShu(){ for (int n = 1; n <= 10000; n++) { int sum = 0; for (int i = 1; i <= (n/2); i++) //除到原来一半就可以了 { if (n % i == 0) { sum += i; } } if (sum == n) { printf ("%d\n", sum); } } } void getWanShuByReduction(){ omp_set_num_threads(5); clock_t start_LiXingLe=clock(); for (int n = 1; n <= 10000; n++) { int sum = 0; #pragma omp parallel for reduction(+:sum) for (int i = 1; i <= (n/2); i++) //除到原来一半就可以了 { if (n % i == 0) { sum += i; } } if (sum == n) { printf ("%d\n", sum); } } clock_t end_LiXingLe=clock(); printf(" reduction并行时间为 :%d\n",end_LiXingLe-start_LiXingLe); }
运行结果: