源代码:

 #include "stdafx.h"  //必须写在首行,因为其前面的include都会被忽略
#include "omp.h"
#include <Windows.h>
#include "time.h"
#include <iostream>
#include <set>
using namespace std;

  //串行方式
set<int> FinishedNumber(int n)
{
set<int> s;
for (int i = ; i <= n; i++)
{
int maxv = (int)(sqrt(double(i)) + );
int sum = ;
for (int j = ; j<maxv; j++)
if (i%j == )
sum += j + i / j;
if (sum == i)
s.insert(i);
}
return s;
}   //并行方式
set<int> FinishedNumber(int n, int p)
{
set<int> s;
omp_set_num_threads(p);
#pragma omp parallel
#pragma omp for
for (int i = ; i <= n; i++)
{
int maxv = (int)(sqrt(double(i)) + );
int sum = ;
for (int j = ; j<maxv; j++)
if (i%j == )
sum += j + i / j;
if (sum == i)
s.insert(i);
}
return s;
} void Test(int step, int count)
{
/*int step=100000;
int count=5;*/
for (int i = ; i <= count; i++)
{
int n = i*step;
clock_t start_Serial = clock(); set<int> result = FinishedNumber(n);
printf("n=%d以内的所有完数为:\n", n);
for (set<int>::iterator it = result.begin(); it != result.end(); it++)
{
/*cout<<*it<<endl;*/
printf("%d\n", *it);
} clock_t end_Serial = clock();
double timeCollapsedSerial = end_Serial - start_Serial;
printf("n=%d, 串行方式运行耗时:%f\n", n, timeCollapsedSerial); int p = ;
double timeCollapsedParallel = ;
for (int power = ; power<; power++)
{
p = pow(, power);
clock_t start_Parallel = clock();
FinishedNumber(n, p);
clock_t end_Parallel = clock();
timeCollapsedParallel = end_Parallel - start_Parallel;
float accelerationRate = timeCollapsedSerial / timeCollapsedParallel;
printf("n=%d, p=%d, 并行方式运行耗时: %f,加速比: %.3f\n", n, p, timeCollapsedParallel, accelerationRate);
} printf("\n");
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int step = * ;
int count = ;
Test(step, count);
system("pause");
}

运行结果:

OpenMP求完数-LMLPHP

04-26 23:50