线性反馈移位寄存器效率

Linear Feedback Shift Register efficiency

我有以下代码实现线性反馈移位寄存器的移位操作:

public int DoShift()
{
    //Find new top bit
    int feedback = Contents & tapSequence;
    int newBit = 0;
    for(int i = 1; i <= length; i++)
    {
        newBit = 1 & (newBit ^ feedback);
        feedback >>= 1;
    }
    //Remember falloff, shift register, add new bit
    int result = Contents & 1;
    Contents >>= 1;
    Contents += newBit << (length - 1);
    return result;
}

哪里

但是,运行 进行了 CPU 使用测试,此功能占用了我 运行 时间的 60%(我认为这是一个相当轻量级方法)。有没有更有效的方法来写这个? 有没有办法用它自己的位对 int 的内容进行异或(以消除 for 循环)?

试试这个:

public int DoShift()
{
    int newBit = 1 << (length - 1); // you can save it as class member
    int result = Contents & 1;
    int feedback = Contents & tapSequence;
    Contents >>= 1;
    while(feedback != 0) {
      feedback &= feedback - 1;
      Contents ^= newBit;
    }
    return result;
}

此外,存在更有效的方法,名为"reversed LSFR"。这是一个想法 - 如果结果为 1,则仅将 tapSequence 应用于整个寄存器一次。

参见示例:https://en.wikipedia.org/wiki/Linear_feedback_shift_register

已采用以下解决方案:

public int DoShift()
{
    //Remember falloff, shift register, add new bit
    int result = Contents & 1;
    Contents = (Contents >> 1) ^ 
        ((CountBits(Contents & tapSequence) % 2) << (length - 1));
    return result;
}

//Brian Kernighan method of counting bits
public static int CountBits(int value)
{
    int count = 0;
    while (value != 0)
    {
        count++;
        value &= value - 1;
    }
    return count;
}

此外,我可能还会尝试并行地 运行 更广泛计划的一些元素。