Jeanno
Jeanno

Reputation: 2859

Optimizing a multiplicator in a nested C++ loop

Hello I have the following snippet

  for(int k = 0; k< 1000; ++k)
    {

        double acc = 1.0;

        if(...)
        {
            short amSeq = 100;

            for (short c = 0; c <= 21; ++c)
            {
                for (short kk = (Range.uSequences[k][c]), s = SeqComp[c]; kk != 0; --kk, --s, --amSeq)
                {
                    acc *= static_cast<double>(s) / amSeq;
                }
            }
        }
        else
            acc = 0;

    }

I was wondering if there is any way to optimize the line acc *= static_cast<double>(s) / amSeq; removing the static_cast speeds up things by a factor of 200 but will obviously yield incorrect results. Thanks

Upvotes: 0

Views: 161

Answers (1)

orlp
orlp

Reputation: 117771

You can easily avoid the conversions by moving code and using the right types:

if(...)
{
    double amSeq = 100;

    for (short c = 0; c <= 21; ++c)
    {
        double s = SeqComp[c];

        for (short kk = (Range.uSequences[k][c]); kk != 0; --kk, --s, --amSeq)
        {
                acc *= s / amSeq;
        }
    }
}

Upvotes: 2

Related Questions