parallel-processing - 每次我增加线程数时,执行时间都会增加。并行执行不应该导致加速吗?
问题描述
Rows 表示已排序的元素数,时间以毫秒为单位:
我已经使用 export 设置线程OMP_NUM_THREADS=n
无论我采用多少元素,执行时间都会不断增加。我哪里错了?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "omp.h"
/*
OpenMP implementation example
Details of implementation/tutorial can be found here:
http://madhugnadig.com/articles/parallel-
processing/2017/02/25/parallel-computing-in-c-using-openMP.html
*/
void mergeSort( int a[], int i, int j);
void merge( int a[], int i1, int j1, int i2, int j2);
int main()
{ clock_t t;
t = clock();
int *a, num, i;
scanf("%d",&num);
a = ( int *)malloc(sizeof(int) * num);
for(i=0;i<num;i++)
scanf("%d",&a[i]);
mergeSort(a, 0, num-1);
printf("\nsorted array :\n");
for(i=0;i<num;i++)
printf("%d ",a[i]);
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC; // in seconds
printf("\n\n\nYour sorting took %f seconds to execute \n", time_taken);
return 0;
}
void mergeSort( int a[], int i, int j)
{
int mid;
if(i<j)
{
mid=(i+j)/2;
#pragma omp parallel sections
{
#pragma omp section
{
mergeSort(a,i,mid); //left recursion
}
#pragma omp section
{
mergeSort(a,mid+1,j); //right recursion
}
}
merge(a,i,mid,mid+1,j); //merging of two sorted sub-arrays
}
}
void merge( int a[], int i1, int j1, int i2, int j2)
{
int temp[1001000]; //array used for merging
int i,j,k;
i=i1; //beginning of the first list
j=i2; //beginning of the second list
k=0;
while(i<=j1 && j<=j2) //while elements in both lists
{
if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}
while(i<=j1) //copy remaining elements of the first list
temp[k++]=a[i++];
while(j<=j2) //copy remaining elements of the second list
temp[k++]=a[j++];
//Transfer elements from temp[] back to a[]
for(i=i1,j=0;i<=j2;i++,j++)
a[i]=temp[j];
}
这就是我在我的 macbook 上运行代码的方式:
解决方案
推荐阅读
- apache-camel - Camel netty4-http 在请求中设置了无效的主机 http 标头
- flutter - 有没有办法在一个容器中包含多个孩子?
- silverstripe - Silverstripe 4 silvershop-core paypal-expr. 税费和运费
- android - 使用此命令在移动设备中运行离子应用程序时出错(离子科尔多瓦运行安卓)
- android - Android 导航组件 - 在包含的模块图之间导航
- android - 在 android ExoPlayer 中添加用于播放加密 .m3u8 流的参数
- netbeans - Netbeans.conf:用户主页的变量是什么?
- javascript - 用户选择:没有在 Safari 中表现不同
- r - 如何使用带有复选框事件 Shiny 的 observeEvent
- javascript - 当我在 html 和 css 中向下滚动时,如何使图像位于菜单栏后面?