源代码:
1 #include "stdafx.h" //必须写在首行,因为其前面的include都会被忽略
2 #include "omp.h"
3 #include <Windows.h>
4 #include "time.h"
5 #include <iostream>
6 #include <set>
7 using namespace std;
8
//串行方式
9 set<int> FinishedNumber(int n)
10 {
11 set<int> s;
12 for (int i = 2; i <= n; i++)
13 {
14 int maxv = (int)(sqrt(double(i)) + 1);
15 int sum = 1;
16 for (int j = 2; j<maxv; j++)
17 if (i%j == 0)
18 sum += j + i / j;
19 if (sum == i)
20 s.insert(i);
21 }
22 return s;
23 }
24
//并行方式
25 set<int> FinishedNumber(int n, int p)
26 {
27 set<int> s;
28 omp_set_num_threads(p);
29 #pragma omp parallel
30 #pragma omp for
31 for (int i = 2; i <= n; i++)
32 {
33 int maxv = (int)(sqrt(double(i)) + 1);
34 int sum = 1;
35 for (int j = 2; j<maxv; j++)
36 if (i%j == 0)
37 sum += j + i / j;
38 if (sum == i)
39 s.insert(i);
40 }
41 return s;
42 }
43
44 void Test(int step, int count)
45 {
46 /*int step=100000;
47 int count=5;*/
48 for (int i = 1; i <= count; i++)
49 {
50 int n = i*step;
51 clock_t start_Serial = clock();
52
53 set<int> result = FinishedNumber(n);
54 printf("n=%d以内的所有完数为:\n", n);
55 for (set<int>::iterator it = result.begin(); it != result.end(); it++)
56 {
57 /*cout<<*it<<endl;*/
58 printf("%d\n", *it);
59 }
60
61 clock_t end_Serial = clock();
62 double timeCollapsedSerial = end_Serial - start_Serial;
63 printf("n=%d, 串行方式运行耗时:%f\n", n, timeCollapsedSerial);
64
65 int p = 0;
66 double timeCollapsedParallel = 0;
67 for (int power = 0; power<6; power++)
68 {
69 p = pow(2, power);
70 clock_t start_Parallel = clock();
71 FinishedNumber(n, p);
72 clock_t end_Parallel = clock();
73 timeCollapsedParallel = end_Parallel - start_Parallel;
74 float accelerationRate = timeCollapsedSerial / timeCollapsedParallel;
75 printf("n=%d, p=%d, 并行方式运行耗时: %f,加速比: %.3f\n", n, p, timeCollapsedParallel, accelerationRate);
76 }
77
78 printf("\n");
79 }
80 }
81 int _tmain(int argc, _TCHAR* argv[])
82 {
83 int step = 1000 * 1000;
84 int count = 5;
85 Test(step, count);
86 system("pause");
87 }
运行结果:
所有评论(0)