每当我增加线程数量时,执行时间就会增加。并行执行不应该导致加速吗?

时间:2018-08-30 16:07:37

标签: parallel-processing openmp

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

Rows represents the number of elements which were sorted and time is in milliseconds

我已使用导出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上运行代码的方式:

This is how I have run the code on my macbook

0 个答案:

没有答案