<pre class="cpp" name="code">//parallel统计完数的并行算法和OpenMP并行编程。
#include "stdafx.h"
#include <omp.h>
#include <iostream>
#include <time.h>
#include <math.h>
#include <stdlib.h>
int isPerfect(int n)
{
int lyy_sum=0;
for(int i = 1; i <=n/2; i++)
if(n%i == 0)
lyy_sum+= i;//统计所有真因子的和。
if(lyy_sum == n)
return 1;//如果与原值相等,则该数为完数。
return 0;//不是完数。
}
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
omp_set_num_threads(2);
int lyy_n,lyy_num=0;
clock_t t1, t2;
long lyy_sumtmp[2];
cin>>lyy_n;
//并行
t1=clock();
#pragma omp parallel
{
long i;
long id=omp_get_thread_num();
long lyy_num1=0;
for(i = id; i < lyy_n; i=i+2)
if(isPerfect(i))
lyy_num1++;
lyy_sumtmp[id]=lyy_num1;
}
for(long i=0;i<2;i++)
lyy_num+=lyy_sumtmp[i];
t2=clock();
cout<<lyy_num-1<<endl;
cout<<"parallel time="<<(t2-t1)<<endl;
//串行
lyy_num=0;
t1=clock();
for(int i = 1; i < lyy_n; i++)
if(isPerfect(i))
lyy_num++;
t2=clock();
cout<<lyy_num<<endl;
cout<<"serial time="<<(t2-t1)<<endl;
system("pause");
return 0;
}
运行结果:
分析:
加速比计算:8253/4134=1.996