Genetic algorithm slowed down in the successive generations

2 views (last 30 days)
I have customized the creation, crossover and mutation functions in Genetic algorithm. The program works without errors but the problem is that its working is slow when the generation reaches 100 or more. Initially an iteration is calculated within 30 seconds but once it reaches the 70th iteration it takes even 3 minutes to compute. What could be the possible reason? Can someone suggest me a method to improve the speed?

Answers (1)

John D'Errico
John D'Errico on 14 Feb 2017
Edited: John D'Errico on 14 Feb 2017
You want us to improve the speed of code that we cannot see, where we have no access to the code?
The crystal ball tells me the answer is in line 37. Or maybe 73. Or is that a speck of dust on the ball?
Seriously, you have told us nothing more than that you wrote code that get slow. If I have to make a wild guess, then you have no clue that dynamic reallocation of variables, growing them as you go, is a BAD thing. This is true in any language, at least any language that allows such dynamic reallocation. If dynamic reallocation is impossible in some other language, then there is no problem, since you cannot do what you are probably doing.
What tends to happen is that a novice thinks that just because they can continuously append elements to an array, that this is a good thing, that it is how you should construct arrays. Instead, MATLAB is forced to reallocate new memory every iteration, copying the entire array to the new location. Obviously this takes more time with each iteration, so it tends to slow down the code as the array gets large. It also fragments memory, potentially causing other problems.
This is perhaps the most common reason why code written by a new user gets very slow with time. But it is only a wild guess.
So instead, preallocate the array (fill with zeros, or better, use NaNs) to be as large as it will be in the end. Then just insert the new elements into the array.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!