簡體   English   中英

乘法矩陣openMP比順序慢

[英]Multiplying matrix openMP is slower than sequential

我是 C 的新手,我創建了一個程序來創建兩個 arrays,然后使用 openMP 將它們相乘。 當我比較它們時,順序比 openMP 方式更快。

#include <stdio.h>
#include <stdio.h>
#include <omp.h>
#include <time.h>
#define SIZE 1000

int arrayOne[SIZE][SIZE];
int arrayTwo[SIZE][SIZE];
int arrayThree[SIZE][SIZE];

int main()
{
  int i=0, j=0, k=0, sum = 0;

  //creation of the first array
  for(i = 0; i < SIZE; i++){
    for(j = 0; j < SIZE; j++){
      arrayOne[i][j] = 2;
      /*printf("%d \t", arrayOne[i][j]);*/
    }
  }

  //creation of the second array
  for(i = 0; i < SIZE; i++){
    for(j = 0; j < SIZE; j++){
      arrayTwo[i][j] = 3;
      /*printf("%d \t", arrayTwo[i][j]);*/
    }
  }

  clock_t begin = clock();
  //Matrix Multiplication (No use of openMP)
  for (i = 0; i < SIZE; ++i) {
      for (j = 0; j < SIZE; ++j) {
          for (k = 0; k < SIZE; ++k) {
              sum = sum + arrayOne[i][k] * arrayTwo[k][j];
          }
          arrayThree[i][j] = sum;
          sum = 0;
      }
  }
  clock_t end = clock();
  double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
  printf("Time taken without openMp: %f  \n", time_spent);

  //Matrix Multiplication Using openMP
  printf("---------------------\n");
  clock_t new_begin = clock();
  #pragma omp parallel private(i, j, sum, k) shared (arrayOne, arrayTwo, arrayThree)
  {
    #pragma omp for schedule(static)
    for (i = 0; i < SIZE; i++) {
      for(j = 0; j < SIZE; j++) {
        for(k = 0; k < SIZE; k++) {
            sum = sum + arrayOne[i][k] * arrayTwo[k][j];
          }
          arrayThree[i][j] = sum;
          sum = 0;
      }
    }
  }
  clock_t new_end = clock();
  double new_time_spent = (double)(new_end - new_begin) / CLOCKS_PER_SEC;
  printf("Time taken WITH openMp: %f  ", new_time_spent);

  return 0;
}

順序方式需要 0.265000,而 openMP 需要 0.563000。 我不知道為什么,有什么解決辦法嗎?

將代碼更新為全局 arrays 並使它們更大,但仍需要雙倍的運行時間。

OpenMP 需要創建和銷毀線程,這會導致額外的開銷。 這樣的開銷非常小,但是對於像您這樣的非常小的工作負載,它仍然很重要。

為了更有效地使用 OpenMP,您應該給它一個較大的工作負載(更大的矩陣),並使與線程相關的開銷不是您運行時的主要因素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM