I am running while loop in 4 thread, in the loop I am evaluating function and incrementally increasing counter.
while(1) {
int fitness = EnergyFunction::evaluate(sequence);
mutex.lock();
counter++;
mutex.unlock();
}
When I run this loop, as I said in 4 running threads, I get ~ 20 000 000 evaluations per second.
while(1) {
if (dist(mt) == 0) {
sequence[distDim(mt)] = -1;
} else {
sequence[distDim(mt)] = 1;
}
int fitness = EnergyFunction::evaluate(sequence);
mainMTX.lock();
overallGeneration++;
mainMTX.unlock();
}
If I add some random mutation for the sequence, I get ~ 13 000 000 evaluations per second.
while(1) {
if (dist(mt) == 0) {
sequence[distDim(mt)] = -1;
} else {
sequence[distDim(mt)] = 1;
}
int fitness = EnergyFunction::evaluate(sequence);
mainMTX.lock();
if(fitness < overallFitness)
overallFitness = fitness;
overallGeneration++;
mainMTX.unlock();
}
But when I add simple if statement that checks, if new fitness is smaller than old fitness if that is true then replace old fitness with new fitness.
But performance loss is massive! Now I get ~ 20 000 evaluations per second. If I remove random mutation part, I also get ~ 20 000 evaluations per second.
Variable overallFitness is declared as
extern int overallFitness;
I am having troubles figuring out what is the problem for such a big performance loss. Is comparing two int such time taking operation?
Also I don't believe that is related to mutex locking.
UPDATE
This performance loss was not because of branch prediction, but compiler just ignored this call int fitness = EnergyFunction::evaluate(sequence);
.
Now I added volatile
and compiler doesn't ignore the call anymore.
Also thank you for pointing out branch misprediction and atomic<int>
, didn't know about them!
Because of atomic I also remove mutex part, so the final code looks like this:
while(1) {
sequence[distDim(mt)] = lookup_Table[dist(mt)];
fitness = EnergyFunction::evaluate(sequence);
if(fitness < overallFitness)
overallFitness = fitness;
++overallGeneration;
}
Now I am getting ~ 25 000 evaluations per second.