Question

tuchin on Tue, 16 May 2017 13:29:05


Made 2 functions without using and using OpenMP.

#include <string>
#include <iostream>
#include <fstream>
#include <Windows.h>
#include <omp.h>

using namespace std;

struct Result
{
  LARGE_INTEGER StopTime, StopTimeNthread, Freq, StartTime, StartTimeNthread;
  long nRes, nResNthread;
  int nthread;
};

Result res;

ofstream fTest;

void sum_arr(const long n) // обычная функция
{
  long sum = 0;
  long* a = (long*)malloc(sizeof(long)*n);
  for(long i = 0; i < n; ++i)
  {
    a[i] = 1;
  }
  QueryPerformanceCounter(&res.StartTime);
  for(long i = 0; i < n; ++i)
  {
    sum += a[i];
  }
  QueryPerformanceCounter(&res.StopTime);
  res.nRes = sum;
  free(a);
}

void sum_arr_omp(const long n) // обычная функция
{
  long sum = 0;
  long* a = (long*)malloc(sizeof(long)*n);
  for(long i = 0; i < n; ++i)
  {
    a[i] = 1;
  }
  res.nthread = omp_get_max_threads();
  QueryPerformanceCounter(&res.StartTimeNthread);
  #pragma omp parallel shared(a) reduction (+: sum) num_threads(res.nthread)
  {
   #pragma omp for    
   for(long i = 0; i < n; ++i)
   {
     sum += a[i];
   }
  } // #pragma omp parallel
  QueryPerformanceCounter(&res.StopTimeNthread);
  res.nResNthread = sum;
  free(a);
}

int main()
{
  setlocale(LC_ALL, "");
  double nMax;
  QueryPerformanceFrequency(&res.Freq);
  fTest.open("Test.txt", ios::app | ios::out | ios::binary);
  sum_arr(1000000);
  sum_arr_omp(1000000);
  nMax = ((double)res.StopTime.QuadPart - (double)res.StartTime.QuadPart)/((double)res.StopTimeNthread.QuadPart 
        - (double)res.StartTimeNthread.QuadPart);
  cout  << nMax << "\t\tefficiency of use " <<  res.nthread << " threads"  << endl;
  fTest << nMax << "\t\tefficiency of use " <<  res.nthread << " threads"  << endl;
  if(res.nRes != res.nResNthread)
    cout << "!!! Error" << endl;
  system("\npause");
  return 0;
}

However, using OpenMP does not give a payoff in time, and even slows down the execution of the program. Help me please. Project https://yadi.sk/d/q5F6DkDV3JD9Aw


Sponsored