▶ 使用 OpenMP 进行奇偶交换排序
● 代码
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <time.h> const int thread = , dataSize = ; int main0(int argc, char* argv[])// 每次并行时即时产生多个线程
{
int i, j, threadReal, data[dataSize];
clock_t time;
if (argc > && *argv[] > ''&& *argv[] < '')
threadReal = atoi(argv[]);
else
threadReal = thread;
srand();
#pragma omp parallel for num_threads(thread)
for (i = ; i < dataSize; i++)
data[i] = rand(); time = clock();
for (i = ; i < dataSize; i++)
{
if (i % )
{
#pragma omp parallel for num_threads(thread) default(none) shared(data, dataSize) private(j)
for (j = ; j < dataSize - ; j += )
{
if (data[j + ] < data[j])
data[j + ] ^= data[j], data[j] ^= data[j + ], data[j + ] ^= data[j];
}
}
else
{
#pragma omp parallel for num_threads(thread) default(none) shared(data, dataSize) private(j)
for (j = ; j < dataSize; j += )
{
if (data[j - ] > data[j])
data[j - ] ^= data[j], data[j] ^= data[j - ], data[j - ] ^= data[j];
}
}
}
time = clock() - time;
printf("Sort finished!\n");
for (i = ; i < dataSize - ; i++)
{
if (data[i] > data[i + ])
{
printf("Sort error at %d, data[i] = %d,data[i+1] = %d, time = %d ms\n", i, data[i], data[i + ], time);
break;
}
}
if (i == dataSize - )
printf("Sort correct, time = %d ms\n", time);
getchar();
return ;
} int main1(int argc, char* argv[])// 预先产生需要的线程
{
int i, j, threadReal, data[dataSize];
clock_t time;
if (argc > && *argv[] > ''&& *argv[] < '')
threadReal = atoi(argv[]);
else
threadReal = thread;
srand();
#pragma omp parallel for num_threads(thread)
for (i = ; i < dataSize; i++)
data[i] = rand(); time = clock();
#pragma omp parallel num_threads(thread) default(none) shared(data, dataSize) private(i, j) // 预先说明并行的参数,特别是规定使用的线程数
for (i = ; i < dataSize; i++) // 注意这层没有 for 子句,且 i 也作为私有变量
{
if (i % )
{
#pragma omp for// 每次并行时使用预先规定的线程数和参数,使用完毕后保留,直到退出外层循环再销毁
for (j = ; j < dataSize - ; j += )
{
if (data[j + ] < data[j])
data[j + ] ^= data[j], data[j] ^= data[j + ], data[j + ] ^= data[j];
}
}
else
{
#pragma omp for
for (j = ; j < dataSize; j += )
{
if (data[j - ] > data[j])
data[j - ] ^= data[j], data[j] ^= data[j - ], data[j - ] ^= data[j];
}
}
}
time = clock() - time;
printf("Sort finished!\n");
for (i = ; i < dataSize - ; i++)
{
if (data[i] > data[i + ])
{
printf("Sort error at %d, data[i] = %d,data[i+1] = %d, time = %d ms\n", i, data[i], data[i + ], time);
break;
}
}
if (i == dataSize - )
printf("Sort correct, time = %d ms\n", time);
getchar();
return ;
}
● 输出结果与对比
// 每次并行时即时产生多个线程,分别为 1 个线程和 8 个线程
Sort finished!
Sort correct, time = ms
Sort finished!
Sort correct, time = ms // 预先产生需要的线程,分别为 1 个线程和 8 个线程
Sort finished!
Sort correct, time = ms
Sort finished!
Sort correct, time = ms