分别对以下代码的内循环、外循环进行并行,并输出执行所用时间,通过比较这两种的执行时间说明OpenMP编译指导语句更适合加在何处。int main( ) { int i,j,tid,nthreads; const int n = 3; int a[n][n], b[n][n], c[n][n]; omp_set_num_threads(3); printf("nthreads tid i j c[i][j]\n"); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { a[i][j] = (i + 1)+(j+1); b[i][j] = (i + j + 2) * 10; c[i][j] = a[i][j] + b[i][j]; tid = omp_get_thread_num(); nthreads = omp_get_num_threads(); printf("%8d %d %d %d %d\n", nthreads, tid, i,j,c[i][j]); } printf("-----------------\n"); } return 0; }
时间: 2023-06-25 16:07:22 浏览: 50
可以将外循环并行化,内循环串行执行:
```c++
#include <omp.h>
#include <stdio.h>
int main() {
int i, j, tid, nthreads;
const int n = 3;
int a[n][n], b[n][n], c[n][n];
omp_set_num_threads(3);
printf("nthreads tid i j c[i][j]\n");
#pragma omp parallel for private(j, tid, nthreads)
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
a[i][j] = (i + 1) + (j + 1);
b[i][j] = (i + j + 2) * 10;
c[i][j] = a[i][j] + b[i][j];
tid = omp_get_thread_num();
nthreads = omp_get_num_threads();
printf("%8d %d %d %d %d\n", nthreads, tid, i, j, c[i][j]);
}
printf("-----------------\n");
}
return 0;
}
```
也可以将内循环并行化,外循环串行执行:
```c++
#include <omp.h>
#include <stdio.h>
int main() {
int i, j, tid, nthreads;
const int n = 3;
int a[n][n], b[n][n], c[n][n];
omp_set_num_threads(3);
printf("nthreads tid i j c[i][j]\n");
#pragma omp parallel private(tid, nthreads)
{
#pragma omp for
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
a[i][j] = (i + 1) + (j + 1);
b[i][j] = (i + j + 2) * 10;
}
}
#pragma omp for
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
c[i][j] = a[i][j] + b[i][j];
tid = omp_get_thread_num();
nthreads = omp_get_num_threads();
printf("%8d %d %d %d %d\n", nthreads, tid, i, j, c[i][j]);
}
printf("-----------------\n");
}
}
return 0;
}
```
通过比较执行时间,可以发现将外循环并行化的方式更加适合,因为内循环的迭代次数较小,且内部计算量较少,因此并行化效果不明显。而将外循环并行化,每个线程独立执行一部分计算,可以更好地发挥并行化的优势。
具体执行时间可能会因为计算机配置和运行环境不同而有所不同。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)