-2

I have a genetic code and I want parallel it on 12 cores, first part is a loop that I want to parallel it, but after parallel and run, I see serial code is faster than parallel code, please tell me where i am wrong. Is there a way that the openmp faster than serrial?

int main() {

srand(time(0));
srand(rand() % 10000007);
G.vertex_degrees();
int step = 0, n_pop = 100;

G.initial_population(n_pop);//parallel shod
G.full_random_array();//movazi shod
clock_t start = clock();
int i = 0,tid,nthreads;
#pragma omp parallel for 
for (i = 0; i < n_pop; i++) {
    G.Chromosome_Repairing_Method(i);
    G.Fitness(i);
}
//cout << "MC Size :" << G.current_Bc_size << " with  Time (precise) = " << ((double)(clock() - start)) / CLOCKS_PER_SEC << "found it" << endl;
omp_set_num_threads(4);

G is an object of genetic algorithm and G.Chromosome_Repairing_Method(i); is a function that repair chromosome and G.Fitness(i); is a function that calculate fitness of each chromosome

sami
  • 7
  • 1
  • 1
    How long are Chromosome_Repairing_Method(), Fitness() ? They better take lot of time for 100 iterations. – coincoin Jan 04 '17 at 07:23
  • I'm wondering if *i* should be declared in the for loop: for(int i = 0, ...). Since i exists outside the scope of the for loop, maybe this is causing an issue. – rcgldr Jan 04 '17 at 09:06
  • 1
    Maybe an issue due to the way you time your code... See [this](http://stackoverflow.com/a/10674970/5239503) or [that](http://stackoverflow.com/a/10736858/5239503) – Gilles Jan 04 '17 at 10:29
  • Besides the issue with using cpu time, your question lacks essential information on the actual loop body, especially the methods of `G`, as well as your specific timing results and system information. – Zulan Jan 04 '17 at 13:10

1 Answers1

0

Parallelizing tasks takes time.

Did you ever have a task in real life and 3 workers and thought by yourself "I will just do it real quick, that will be faster than explaining what needs to be done to those three guys"?

Well, the same thing might have happened here. One guy "just doing it" was faster than multiple guys organizing it, doing it and organizing again to merge results.

Doing stuff in parallel is no silver bullet. The tasks need to be suited for it or you will only add overhead.

nvoigt
  • 75,013
  • 26
  • 93
  • 142