Search code examples
c++algorithmoptimizationrandomrandom-access

randomly choosing an empty vector element, when it is possible to know beforehand which are full


I finally determined that this function is responsible for the majority of my bottleneck issues. I think its because of the massively excessive random access that happens when most of the synapses are already active. Basically, as the title says, I need to somehow optimize the algorithm so that I'm not randomly checking a ton of active elements before landing on one of the few that are left.

Also, I included the whole function in case of other flaws that can be spotted.

void NetClass::Explore(vector <synapse> & synapses, int & n_syns)   //add new synapses
{
    int size = synapses.size();
    assert(n_syns <= size );

    //Increase the age of each active synapse by 1
    Age_Increment(synapses);

    //make sure there is at least one inactive vector left
    if(n_syns == size)
        return;

        //stochastically decide whether a new connection is added
        if((rand_r(seedp) %1000) < ( x / (1 +(n_syns * ( y / 100)))))  
        {
            n_syns++; //a new synapse has been created

            //main inefficiency here
            while(1)
            {
                int syn = rand_r(seedp) % (size);
                if (!synapses[syn].active)
                {
                    synapses[syn].active = true;
                    synapses[syn].weight = .04 + (float (rand_r(seedp) % 17) / 100);     
                    break;
                }
            }
        }  
}

void NetClass::Age_Increment(vector <synapse> & synapses)  
{
    for(int q=0, int size = synapses.size(); q < size; q++)
        if(synapses[q].active)
            synapses[q].age++;
}

Solution

  • Pass a random number, k, in the range [0, size-n_syns) to Age_Increment. Have Age_Increment return the kth empty slot.