Initialize Arrays

General OpenMP discussion

Initialize Arrays

Postby waruna » Tue Aug 19, 2008 4:56 am

Hi all,
I wrote a simple programme (C++) to initialize an integer Array. But if I add OpenMP, it takes much more time to get initialized.
What could be the problem
Without OpenMP: 0.354937 seconds
With OpenMP: 3.2207 seconds

The programme is given below

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

using namespace std;

#define SIZE 10000000

int main (int argc, char *argv[])
int *iArray = new int[SIZE];
#pragma omp parallel default(shared)
#pragma omp for schedule(static, SIZE/2)
for (int i = 0; i < SIZE; i++)
iArray[i] = rand();

Thank You,
Waruna Ranasinghe

Re: Initialize Arrays

Postby ejd » Tue Aug 19, 2008 6:43 am

You don't say what compiler you are using, so I can't be sure. However, this is a trap that many people starting to use OpenMP seem to fall into. The call to rand within the loop has to be protected because there are global values used to generate the random numbers. This means that to have rand be thread safe and still give random numbers, locks have to be used. This slows rand down considerably - making it worse than doing it sequentially. If you really are trying to initialized an array with random numbers in parallel, then you need a parallel random number generator. Try changing the initialization of iArray from using rand to a call to a function that initializes iArray using some arithmetic expression and you will see that the time used is much more reasonable.
Posts: 1025
Joined: Wed Jan 16, 2008 7:21 am

Return to Using OpenMP

Who is online

Users browsing this forum: No registered users and 5 guests