优化嵌套C ++循环中的乘数

时间:2012-04-18 19:14:54

标签: c++ optimization loops nested

您好我有以下代码段

  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;

    }

我想知道是否有任何方法可以优化行acc *= static_cast<double>(s) / amSeq;,将static_cast的速度提高200倍,但显然会产生不正确的结果。感谢

1 个答案:

答案 0 :(得分:2)

您可以通过移动代码并使用正确的类型轻松避免转换:

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;
        }
    }
}