OpenMP缓慢减少

时间:2011-06-08 15:36:45

标签: c++ openmp

我编写简单的C ++代码来计算数组减少总和,但是使用OpenMP减少程序的工作很慢。程序有两种变体:一种是最简单的总和,另一种是复杂数学函数的总和。在代码中,复杂变体被评论。

#include <iostream>
#include <omp.h>
#include <math.h>

using namespace std;

#define N 100000000
#define NUM_THREADS 4

int main() {

  int *arr = new int[N];

  for (int i = 0; i < N; i++) {
    arr[i] = i;
  }

  omp_set_num_threads(NUM_THREADS);
  cout << NUM_THREADS << endl;

  clock_t start = clock();
  int sum = 0;
  #pragma omp parallel for reduction(+:sum)
  for (int i = 0; i < N; i++) {
    // sum += sqrt(sqrt(arr[i] * arr[i])); // complex variant
    sum += arr[i]; // simple variant
  }

  double diff = ( clock() - start ) / (double)CLOCKS_PER_SEC;
  cout << "Time " << diff << "s" << endl;

  cout << sum << endl;

  delete[] arr;

  return 0;
}

我是由ICPC和GCC编译的:

icpc reduction.cpp -openmp -o reduction -O3
g++ reduction.cpp -fopenmp -o reduction -O3

处理器:Intel Core 2 Duo T5850,操作系统:Ubuntu 10.10

有使用和不使用OpenMP编译的简单和复杂变体的执行时间。

简单变体“sum + = arr [i];”:

icpc
0.1s without OpenMP
0.18s with OpenMP

g++
0.11c without OpenMP
0.17c with OpenMP

复杂变体“sum + = sqrt(sqrt(arr [i] * arr [i]));”:

icpc
2,92s without OpenMP
3,37s with OpenMP

g++ 
47,97s without OpenMP
48,2s with OpenMP

在系统监视器中,我看到2个内核在OpenMP程序中工作,1个内核在没有OpenMP的程序中工作。我将在OpenMP中尝试几个线程并且没有加速。我不明白为什么减速很慢。

2 个答案:

答案 0 :(得分:4)

函数clock()测量整个过程消耗的处理器时间,因此打印时间显示所有线程消耗的时间总和。如果你想看到壁垒时间(从开始到结束的实时时间),请使用例如POSIX系统上的times()功能

答案 1 :(得分:1)

您正在做的事情非常简单,以至于您可能受到内存带宽的限制。我很少得到任何加速,直到工作远远超过从工作中获取数据所需的时间。另外,减少还有额外的工作来合并所有子结果。