并行计算—OpenMP—统计完数个数

<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



  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值