您的位置:首页 > 运维架构

并行计算—OpenMP—统计素数的个数

2016-12-12 12:06 453 查看
//统计素数个数的并行算法和OpenMP并行编程。
#include "stdafx.h"
#include <omp.h>
#include <iostream>
#include <time.h>
#include <math.h>
#include <stdlib.h>
using namespace std;

int isPrime(int lyy_num)   //判断是否为素数
{
int lyy_flag=1;
int lyy_s=sqrt(lyy_num*1.0);
for(int j=2;j<=lyy_s;j++)
{
if(lyy_num%j==0)
{
lyy_flag=0;
break;
}
}
return lyy_flag;
}
int _tmain(int argc, _TCHAR* argv[])
{
omp_set_num_threads(2);
int lyy_n,lyy_num=0;
clock_t t1, t2;
cin>>lyy_n;
//并行
t1=clock();
#pragma omp parallel for reduction(+:lyy_num)   //reduction方法实现并行
for(int i=2;i<=lyy_n;i++)
lyy_num+=isPrime(i);
t2=clock();
cout<<lyy_num<<endl;
cout<<"parallel time="<<(t2-t1)<<endl;
//串行
lyy_num=0;
t1=clock();
for(int i=2;i<=lyy_n;i++)
lyy_num+=isPrime(i);
t2=clock();
cout<<lyy_num<<endl;
cout<<"serial time="<<(t2-t1)<<endl;

system("pause");
return 0;
}

运行结果:



分析:

   加速比计算:219/156=1.404


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  openmp 并行计算