我正在尝试使用openMP使我的快速排序算法并行化。在实现openMP之后,我的加速快排的尝试失败了,我的快排将数组排序的速度减慢了近一倍。以下是我实现openMP的代码:
void quickSort( int a[], int l, int r) {
int j;
if( l < r ) {
#pragma omp parallel
{
j = partition( a, l, r);
#pragma omp sections
{
#pragma omp section
{
quickSort( a, l, j-1);
}
#pragma omp section
{
quickSort( a, j+1, r);
}
}
}
}
}
整个排序过程发生在 partition 方法中,如果您对它的工作方式感兴趣,这里是代码:
int partition( int a[], int l, int r) {
int pivot, i, j, t;
pivot = a[l];
i = l; j = r+1;
while(1) {
do ++i; while( a[i] <= pivot && i <= r );
do --j; while( a[j] > pivot );
if( i >= j ) break;
t = a[i]; a[i] = a[j]; a[j] = t;
}
t = a[l]; a[l] = a[j]; a[j] = t;
return j;
}
我在主函数中调用 quickSort 前花费了一些时间,在 main 函数中的 printf 之前停止计时器。 线程数量定义为10(我已在我的电脑上尝试过4、2和1)。在对包含100万个介于0-100之间的随机整数的列表进行排序后,我的结果如下:
没有使用 OpenMP 的时间在6.48004至5.32001之间。
使用 OpenMP 的时间在11.8309至10.6239之间(使用2-4个线程)。
这是怎么回事?