I've been trying to parallelize Quick Sort using OpenMP, but it seems that I've done something wrong on that part since the more threads used the slower it goes!
I know there is always overhead included, but increasing number of threads in a giant list should make it faster and not slower (my case).
Here is the code enjoy!
#include <omp.h>
double start_time, end_time;
#include <stdio.h>
#define MAXSIZE 10000 /* maximum array size */
#define MAXWORKERS 8 /* maximum number of workers */
int numWorkers;
int size;
int doge[MAXSIZE];
void breakdown(int, int);
/* read command line, initialize, and create threads */
int main(int argc, char *argv[]) {
srand(time(NULL));
int i;
/* read command line args if any */
size = (argc > 1)? atoi(argv[1]) : MAXSIZE;
numWorkers = (argc > 2)? atoi(argv[2]) : MAXWORKERS;
if (size > MAXSIZE) size = MAXSIZE;
if (numWorkers > MAXWORKERS) numWorkers = MAXWORKERS;
for(i = 0;i<size;i++){
doge[i] = 1+rand()%99;
}
omp_set_num_threads(numWorkers);
start_time = omp_get_wtime();
#pragma omp parallel
{
#pragma omp single nowait
{
breakdown(0, size);
}
}
end_time = omp_get_wtime();
for(i = 0;i<size;i++){
printf("%d ", doge[i]);
}
printf("it took %g seconds\n", end_time - start_time);
}
void breakdown(int from, int to){
if(to-from < 2){
return;
}
int left, right, temp;
int i_pivot = from + rand()%(to-from);
int pivot = doge[i_pivot];
left = from;
right = to;
while (left <= right){
if (doge[left] > pivot){
/* swap left element with right element */
temp = doge[left];
doge[left] = doge[right];
doge[right] = temp;
if (right == i_pivot)
i_pivot = left;
right--;
}
else
left++;
}
/* place the pivot in its place (i.e. swap with right element) */
temp = doge[right];
doge[right] = pivot;
doge[i_pivot] = temp;
#pragma omp task
{
breakdown(from, right - 1);
}
#pragma omp task
{
breakdown(right + 1, to);
}
//implicit DOGE
}
I believe I've done the parallalization wrong in short.. these lines:
#pragma omp parallel
{
#pragma omp single nowait
{
breakdown(0, size);
}
}
AND
#pragma omp task
{
breakdown(from, right - 1);
}
#pragma omp task
{
breakdown(right + 1, to);
}
Any help would be doge