首页 > 解决方案 > 每次我增加线程数时,执行时间都会增加。并行执行不应该导致加速吗?

问题描述

Rows 表示已排序的元素数,时间以毫秒为单位:

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 上运行代码的方式:

这就是我在我的 macbook 上运行代码的方式

标签: parallel-processingopenmp

解决方案


推荐阅读