gpt4 book ai didi

c++ - 使用 OPENMP 的并行归并排序

转载 作者:行者123 更新时间:2023-11-28 07:59:12 28 4
gpt4 key购买 nike

我写了一个顺序归并排序程序如下:

#include "stdafx.h"
#include "iostream"
#include "omp.h"
#include "fstream"
using namespace std;

int a[50];
void merge(int,int,int);
void merge_sort(int low,int high)
{
int mid,newval;
double clock, clock1,clock2;
if(low<high)
{
mid=(low+high)/2;
#pragma omp parallel shared(low,mid,high) num_threads(2)
{
//newval=omp_get_thread_num();
//cout<<"thread: "<<newval<<endl;
merge_sort(low,mid);
clock=omp_get_wtime();
//cout<<"Clock: "<<clock<<endl;
merge_sort(mid+1,high);
merge(low,mid,high);
clock1=omp_get_wtime();
//cout<<"Clock1: "<<clock<<endl;
clock2=clock1-clock;
cout<<"Clock2: "<<clock2<<endl;
}
//cout<<"valud=%d"<<low<<endl;
}
}
void merge(int low,int mid,int high)
{
int h,i,j,b[50],k;
h=low;
i=low;
j=mid+1;

while((h<=mid)&&(j<=high))
{
if(a[h]<=a[j])
{
b[i]=a[h];
h++;
}
else
{
b[i]=a[j];
j++;
}
i++;
}
if(h>mid)
{
for(k=j;k<=high;k++)
{
b[i]=a[k];
i++;
}
}
else
{
for(k=h;k<=mid;k++)
{
b[i]=a[k];
i++;
}
}
for(k=low;k<=high;k++) a[k]=b[k];
}

void main()
{
int num,i;
int clock_n,len;
FILE *fp;
char *buf;
char *newchat;//ifstream properfile;


cout<<"********************************************************************************"<<endl;
cout<<" MERGE SORT PROGRAM"<<endl;

cout<<"********************************************************************************"<<endl;
cout<<endl<<endl;
cout<<"Please Enter THE NUMBER OF ELEMENTS you want to sort [THEN PRESS ENTER]:"<<endl;
cout<<endl;
//cout<<"Now, Please Enter the ( "<< num <<" ) numbers (ELEMENTS) [THEN PRESS ENTER]:"<<endl;
//for(i=1;i<=num;i++)
//{
fp=fopen("E:\\Study\\Semester 2\\Compsci 711- Parallel and distributed computing\\Assignment\\sample_10.txt","rb");
fseek(fp,0,SEEK_END); //go to end
len=ftell(fp); //get position at end (length)
cout<<"Length is %d"<<len<<endl;
//fseek(fp,0,SEEK_SET); //go to beg.
buf=(char *)malloc(len); //malloc buffer
newchat=buf;
fread(newchat,len,1,fp); //read into buffer
fclose(fp);
//cout<<"Read %c"<<newchat<<endl;

////cin>>num;


//}

merge_sort(1,len);

cout<<endl;
cout<<"So, the sorted list (using MERGE SORT) will be :"<<endl;
cout<<endl<<endl;

for(i=1;i<=num;i++)
cout<<a[i]<<" ";
cout<<endl<<endl<<endl<<endl;

}

现在我想并行化这段代码(C 中用于并行化的 API 是 OPENMP)。你能帮助我吗?基本上我使用 #pragma parallel num_thread(4) 但我不知道我是否应该包含任何其他内容以进行并行化。

最佳答案

合并排序算法的主要瓶颈是合并函数。它的复杂度是 O(n)。前几次合并操作的成本将主导整个应用程序的成本。对更大的阵列使用优化的并行算法。

对于较小的数组(<20 个元素),请避开障碍。实际上我更喜欢顺序 O(n^2) 算法。

你不应该使用部分而不是 #pragma omp parallel shared(low,mid,high) num_threads(2)

关于c++ - 使用 OPENMP 的并行归并排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11944457/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com