【发布时间】:2023-04-04 23:53:01
【问题描述】:
我正在尝试对更大的矩阵(1000x1000 到 5000x5000 双精度)进行乘法运算。我必须使用 OpenMP 来并行化乘法。并行 for 循环由 p 个线程处理,我猜它们是根据打印出 omp_get_thread_num() 正确调度的。 我在 4 核 CPU 上运行,并确认最大线程数为 4。如果这有什么不同,CPU 是虚拟的。 问题是当我更改线程的 nb 时运行时间并没有减少。
我检查了
libgomp库是由ldconfig -p | grep -i "gomp"安装的。我已尝试将并行循环的位置更改为嵌套循环之一。
我已尝试更改调度和块大小。
#include <stdio.h> #include <stdlib.h> #include <omp.h> #include <time.h> double** createMatrix(int N) { double** rndMatrix; srand48((long int)time(NULL)); rndMatrix = malloc(sizeof(double*)*N); int n,m; for(n=0; n<N; n++){ rndMatrix[n] = malloc(sizeof(double*)*N); for (m=0;m<N;m++){ rndMatrix[n][m] = drand48(); } } return rndMatrix; } void problem1(double** a, double** b, int N, int p){ int i,k,j; int g; double** c; c = malloc(sizeof(double*)*N); for(g=0; g<N; ++g) c[g] = malloc(sizeof(double*)*N); //Timer start clock_t tStart = clock(); //time_t tStart, tEnd; //tStart =time(NULL); //Parallelised part #pragma omp parallel shared(a,b,c,N) private(i,k,j) num_threads(p) { #pragma omp for schedule(static) nowait for(i=0; i<N; ++i){ for(j=0; j<N; ++j){ double sum = 0; for(k=0; k<N; ++k){ sum += a[i][k] * b[k][j]; } c[i][j]=sum; } } } //Timer end printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC); //tEnd = time(NULL); //printf("Time taken: %ds\n", tEnd - tStart); } int main(void) { int p=0; int N=0; //User input: printf("Enter matrix dimension:\n"); scanf("%d", &N); printf("Please enter nb of threads:\n"); scanf("%d", &p); double **a; double **b; a = createMatrix(N); sleep(2); b = createMatrix(N); problem1(a,b,N,p); return 0; }
【问题讨论】:
-
1) 你如何测量时间 2) 你运行它的确切处理器是什么? 3)你如何编译代码? 4) 请提供minimal reproducible example
-
1) 如代码所示,我同时使用了clock() 和time()。 2)lscpu的结果可以在添加的图片中看到。 3) gcc -o3 -fopenmp openmpMain.c o2 或 o3 需要分配 4) 我将上面的代码编辑为可运行
-
您使用
clock和time得到相同的结果吗? -
结果是一样的。除了那个clock()返回了更多的小数。
标签: c parallel-processing openmp