Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22018

Why Parallel Merge sort runs faster with single thread?

$
0
0

I have the following Parallel Merge sort algorithm in openMP. OpenMP creates 8 threads by default, but it is way slower than sequential. But when I specify omp_set_num_threads(1), i.e. set number of threads to one, the time is faster than the sequential one. Any plausible explanation to this?

void para_merge_sort(int para_arr[], int low, int high)
{
    if (low < high)
    {
        int med = low + (high-low)/2;
        #pragma omp task firstprivate(para_arr, low, med)
        para_merge_sort (para_arr, low, med);
        #pragma omp task firstprivate(para_arr, med, high)
        para_merge_sort (para_arr, med+1, high);
        #pragma omp taskwait
        merge (para_arr, low, med, high);
    }
}

void merge_sort()
{
    int seq_arr[MAX], para_arr[MAX];
    omp_set_num_threads(1);

    for (int i=0; i<MAX; ++i)
        seq_arr[i] = para_arr[i] = rand()%100;

    double start_time = omp_get_wtime();
    seq_merge_sort(seq_arr, 0, MAX-1);
    double comp_time = omp_get_wtime() - start_time;
    printf ("Sequential merge sort : %f\n", comp_time);

    start_time = omp_get_wtime();
    #pragma omp parallel
    {
        #pragma omp single
        para_merge_sort(para_arr, 0, MAX-1);
    }
    comp_time = omp_get_wtime() - start_time;
    printf ("Parallel merge sort : %f\n", comp_time);

    /*for (int i=0; i<MAX; ++i)
        printf ("%d\n", para_arr[i]);*/
}

Sequential merge sort : 0.004533

Parallel merge sort : 0.007102

when omp_set_num_threads(1) :

Sequential merge sort : 0.005124

Parallel merge sort : 0.002424


Viewing all articles
Browse latest Browse all 22018

Trending Articles