基于OpenMP的C++并行编程简单示例

示例要求:在整数A和B之间找到符合条件的值X,使f(X)=C。

示例代码(需要在VS中开启OpenMP支持):

 1 #include
 2 #include
 3 #include"omp.h"
 4 
 5 int f(int i) {
 6     int i4_huge = 2147483647;
 7     int j;
 8     int k;
 9     int value;
10     value = i;
11     for (j = 1; j <= 5; j++)
12     {
13         k = value / 127773;
14         value = 16807 * (value - k * 127773) - k * 2836;
15         if (value <= 0)
16         {
17             value = value + i4_huge;
18         }
19     }
20     return value;
21 }
22 
23 int search(int a, int b, int c)
24 {
25     int fi;
26     int i;
27     int j;
28 
29     j = -1;
30 
31     #pragma omp parallel for num_threads(6)
32     for (i = a; i <= b; i++)
33     {
34         fi = f(i);
35         if (fi == c)
36         {
37             j = i;
38             break;
39         }
40     }
41 
42     return j;
43 }
44 
45 
46 int main()
47 {
48     int j;
49     int a = 1;
50     int b = 10000000;
51     int c = 45;
52     double wtime;
53 
54     clock_t start, finish;
55     double totaltime;
56     start = clock();
57 
58     j = search(a, b, c);
59 
60     finish = clock();
61     totaltime = (double)(finish - start) / CLOCKS_PER_SEC;
62     std::cout << "\n search运行时间为" << totaltime << "秒!" << std::endl;
63     system("pause");
64     return 0;
65 }
View Code

并行算法的加速情况:

加速前:

基于OpenMP的C++并行编程简单示例_第1张图片

加速后:

基于OpenMP的C++并行编程简单示例_第2张图片

 

转载于:https://www.cnblogs.com/GISQZC/p/9333312.html

你可能感兴趣的:(基于OpenMP的C++并行编程简单示例)