Fast mutation implementation for genetic algorithms in Python
The other day I was playing to see how much I could squeeze out of a genetic algorithm written in Python. The code below shows the example I used. The first part implements a simple two loop version of a traditional allele random mutation. The second part is coded using numpy 2D arrays. The code also measures the time spent on both implementations using cProfile. from numpy import * pop_size = 2000 l = 200 z = zeros((pop_size,l)) def mutate () : for i in xrange(pop_size): for j in xrange(l) : if random.random()<0.5 : z[i,j] = random.random() import cProfile cProfile.run('mutate()') def mutate_matrix () : r = random.random(size=(pop_size,l))<0.5 v = random.random(size=(pop_size,l)) k = r*v + logical_not(r)*z cProfile.run('mutate_matrix()') If you run the code listed above you may get something similar to ...