openMP编程,求前缀和,注意事项

本文介绍了两种使用OpenMP求前缀和的并行方法,并对比了与串行计算的效率。在实验中发现,随着数据量增加,串行和并行时间差距减小,且首次并行可能因缓存加载导致较慢。伪共享问题成为性能瓶颈,解决方案包括创建局部拷贝或调整数组间隔。此外,文中讨论了parallel与parallel for的选择,以及private变量的初始化和双层for的使用注意事项。
摘要由CSDN通过智能技术生成

1.本文列出两种求前缀和的并行方法和与串行的比较。

2.第一种方法:


代码如下:

#include <iostream> 
#include <omp.h>
#include <ctime>
#include <cstdlib>
using namespace std;
const int maxn = 10000000;
const int maxn1 = 23;
const int maxn2 = 5000000;
int a[maxn];
int b[maxn1][maxn2];
int c[maxn1][maxn2];
int temp;
int n=10;
void sCompute();
void pCompute();
int main()
{
	while(true){
	cout << "enter n(-1 to quit) : " << endl;
	cin >>n;
	if(n==-1) return 0;
	temp = pow(2,n);
	pCompute();
	sCompute();
	}
	system("pause");
	return 0;
}


void pCompute()
{
	double start = omp_get_wtime();
	int i,j,h;
		
	#pragma omp parallel for shared(a) private(i)
	for ( i= 1; i <=temp; i=i+1)
	{
		a[i] = i;
	}
	#pragma omp parallel for shared(a,b) private(j)
	
	for (  j = 1; j <= temp; j=j+1 )
	{
		b[0][j] = a[j];
	}
	
	int temp1 = n;
	
	#pragma omp parallel for shared(b) private(j,h)
	for (  h = 1; h <= temp1; h++)
	{
		int temp2 = temp/pow(2,h);
		
		for (  j = 1; j <= temp2; j++)
		{
			b[h][j]=b[h-1][2*j-1]+b[h-1][2*j];
		}
	}

	#pragma omp parallel for shared(c,b) private(j,h)
	for ( h = temp1; h>=0; h--)
	{
		for (j = 1; j <= temp/pow(2,h); j++)
		{
			if(j%2==0) c[h][j]=c[h+1][j/2];
			if(j==1) c[h][1]=b[h][1];
			if(j%2==1&&j>1) c[h][j]=c[h+1][(j-1)/2]+b[h][j];
		}
	}
	
	double end = omp_get_wtime();
	
	cout << " the time for parallel: " << end-start<<endl;
	
}

void sCompute()
{
	double start = omp_get_wtime();

	for ( int i= 1; i <=temp; i++)
	{
		a[i] = i;
	}
	//#pragma omp parallel sections
	for ( int j = 1; j <= temp; j++ )
	{
		b[0][j] = a[j];
	}
	int temp1 = n;
	
	for ( int h = 1; h <= temp1; h++)
	{
		int temp2 = temp/pow(2,h);
		
		for ( int j = 1; j <= temp2; j++)
		{
			b[h][j]=b[h-1][2*j-1]+b[h-1][2*j];
		}
	}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值