gpt4 book ai didi

c - Duff 的设备是如何工作的?

转载 作者:太空狗 更新时间:2023-10-29 16:14:24 25 4
gpt4 key购买 nike

我读过 article on Wikipedia on the Duff's device ,我不明白。我真的很感兴趣,但是我已经读了好几遍那里的解释,但我仍然不明白 Duff 的设备是如何工作的。

更详细的解释是什么?

最佳答案

其他地方有一些很好的解释,但让我试一试。 (这在白板上要容易得多!)这是带有一些符号的维基百科示例。

假设您要复制 20 个字节。第一遍程序的流程控制是:

int count;                        // Set to 20
{
int n = (count + 7) / 8; // n is now 3. (The "while" is going
// to be run three times.)

switch (count % 8) { // The remainder is 4 (20 modulo 8) so
// jump to the case 4

case 0: // [skipped]
do { // [skipped]
*to = *from++; // [skipped]
case 7: *to = *from++; // [skipped]
case 6: *to = *from++; // [skipped]
case 5: *to = *from++; // [skipped]
case 4: *to = *from++; // Start here. Copy 1 byte (total 1)
case 3: *to = *from++; // Copy 1 byte (total 2)
case 2: *to = *from++; // Copy 1 byte (total 3)
case 1: *to = *from++; // Copy 1 byte (total 4)
} while (--n > 0); // N = 3 Reduce N by 1, then jump up
// to the "do" if it's still
} // greater than 0 (and it is)
}

现在,开始第二遍,我们只运行指示的代码:

int count;                        //
{
int n = (count + 7) / 8; //
//

switch (count % 8) { //
//

case 0: //
do { // The while jumps to here.
*to = *from++; // Copy 1 byte (total 5)
case 7: *to = *from++; // Copy 1 byte (total 6)
case 6: *to = *from++; // Copy 1 byte (total 7)
case 5: *to = *from++; // Copy 1 byte (total 8)
case 4: *to = *from++; // Copy 1 byte (total 9)
case 3: *to = *from++; // Copy 1 byte (total 10)
case 2: *to = *from++; // Copy 1 byte (total 11)
case 1: *to = *from++; // Copy 1 byte (total 12)
} while (--n > 0); // N = 2 Reduce N by 1, then jump up
// to the "do" if it's still
} // greater than 0 (and it is)
}

现在,开始第三遍:

int count;                        //
{
int n = (count + 7) / 8; //
//

switch (count % 8) { //
//

case 0: //
do { // The while jumps to here.
*to = *from++; // Copy 1 byte (total 13)
case 7: *to = *from++; // Copy 1 byte (total 14)
case 6: *to = *from++; // Copy 1 byte (total 15)
case 5: *to = *from++; // Copy 1 byte (total 16)
case 4: *to = *from++; // Copy 1 byte (total 17)
case 3: *to = *from++; // Copy 1 byte (total 18)
case 2: *to = *from++; // Copy 1 byte (total 19)
case 1: *to = *from++; // Copy 1 byte (total 20)
} while (--n > 0); // N = 1 Reduce N by 1, then jump up
// to the "do" if it's still
} // greater than 0 (and it's not, so bail)
} // continue here...

现在复制了 20 个字节。

注意:原始 Duff 设备(如上所示)已复制到位于 to 地址的 I/O 设备。因此,没有必要将指针 *to 递增。在两个内存缓冲区之间复制时,您需要使用 *to++

关于c - Duff 的设备是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/514118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com